ct4242
ct4242

Reputation: 33

Approximating Numerical 2nd Derivative with Python

To preface this question, I understand that it could be done better. But this is a question in a class of mine and I must approach it this way. We cannot use any built in functions or packages.

I need to write a function to approximate the numerical value of the second derivative of a given function using finite difference. The function is below we are using.

2nd Derivative Formula (I lost the login info to my old account so pardon my lack of points and not being able to include images).

My question is this:

I don't understand how to make the python function accept the input function it is to be deriving. If someone puts in the input 2nd_deriv(2x**2 + 4, 6) I dont understand how to evaluate 2x^2 at 6.

If this is unclear, let me know and I can try again to describe. Python is new to me so I am just getting my feet wet.

Thanks

Upvotes: 3

Views: 2624

Answers (2)

Bruce
Bruce

Reputation: 7132

you can't pass a literal expression, you need a function (or a lambda).

def d2(f, x0, h = 1e-9):
   func = f
   if isinstance(f, str):
      # quite insecure, use only with controlled input
      func = eval ("lambda x:%s" % (f,))
   return (func(x0+h) - 2*func(x0) + func(x0-h))/(2*h)

Then to use it

def g(x):
   return 2*x**2 + 4

# using explicit function, forcing h value
print d2(g, 6, 1e-10)

Or directly:

# using lambda and default value for h
print d2(lambda x:2x**2+4, 6)

EDIT

  • updated to take into account that f can be a string or a function

Upvotes: 0

ewcz
ewcz

Reputation: 13087

you can pass the function as any other "variable":

def f(x):
    return 2*x*x + 4

def d2(fn, x0, h):
    return (fn(x0+h) - 2*fn(x0) + fn(x0-h))/(h*h)

print(d2(f, 6, 0.1))

Upvotes: 3

Related Questions