2

I'm a beginner with Python (v 3.7) and I am trying to evaluate numerically a derivative of a symbolic function that contains parameters but I can't feed the values in a successful way.

I've tried different combinations getting inspiration from reading this question and something also from here.

Here is a minimal example that replicates my problem:

import sympy as sym
from sympy import*

x, y, a = sym.var('x, y, a')
def f(x,y):
    return a*x**2 + x*y**2
fprime = sym.diff(f(x,y),x)

print(f(1,1))
print(fprime.evalf(subs={x: 1, y: 1}))

As expected the output of the first print is a+1 but the issue arrives with the second print because the output I get is 2.0*a*x + y**2 while I wish to obtain 2*a+1.

How shall I amend my code? I've also tried defining fprime separately and run the following:

def fprime(x,y):
    return sym.diff(f(x,y),x)
print(fprime(x,1))

but still I can't make any progress. Thanks!

GabMac
  • 123
  • 5

1 Answers1

1

Just use substitution. Use evalf when you are trying to get a number from an expression that is a number. Your, containing unevaluated a is not yet a number so evaluation rejects it.

>>> fprime.subs({x: 1, y: 1})
2*a + 1
smichr
  • 16,948
  • 2
  • 27
  • 34