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
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