0

I wrote a function that computes the value of the derivative when passing arguments, but when passing a function with abs() the results are symbols instead of floats. However, the result I need to round to 2 decimal places and I can't figure out how to fix it

from sympy import * 
import numpy as np

global x, y, z, t 
x, y, z, t = symbols("x, y, z, t")    
def req1(f, g, a): 

    dfg = diff(f + g, x)

    res = round(dfg.subs(x, a), 2)

    return res
1
  • could you show us full working code , example and the error message you have so we can reproduce and help ? Commented Dec 24, 2021 at 17:09

1 Answer 1

0

round is a numeric Python function. It doesn't understand about sympy objects.

To get a numeric approximation of a constant sympy expression, you can use evalf():

from sympy import sqrt, symbols

x = symbols('x')
f = sqrt(x)
f.subs(x, 2)  # sqrt(2)
f.subs(x, 2).evalf()  # 1.41421356237310

Once the result is numeric, you can use Python's (or numpy's) numeric functions:

round(f.subs(x, 2).evalf(), 2)  # 1,41

Sympy also has a round() function, that first does a numeric approximation, and then rounds. (Sympy's round can't be called stand-alone, it needs to be called as expression.round().

f.subs(x, 2).round(2)  # 1.41
Sign up to request clarification or add additional context in comments.

1 Comment

Did you try x = symbols('x'), f = sqrt(x) and f.subs(x, 2).round(2)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.