3

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

ct4242
  • 33
  • 5
  • Not very familiar with this, but I was looking at `exec` some time ago, which allows you to compile some piece of code from user input. If you want to write a function that can derive any user-input function, this is the way to go, I guess. However, if your problem is just the parsing of the input, this can be done, for example, with `out1 = inputstr.split('(')` followed by `out2 = out1[1].split(', ')`. – nostradamus Aug 25 '16 at 14:44
  • what are the rules for the input? – Ma0 Aug 25 '16 at 14:48
  • @Ev.Kounis Without speaking with the professor, it seems like it is any single variable expression. – ct4242 Aug 25 '16 at 15:45
  • I was not clear, I think the input will be formatted for python. I just need to process it in the function – ct4242 Aug 25 '16 at 15:49
  • @ct4242 writing a function that takes the users input and tries to convert it to something `eval` can work with is not difficult for the simple cases. For example `^` can be easily replaced with `**`. And for the multiplications try to look for 2 characters in a row for which the first `pair[0]` returns `True` when `pair[0].isnumeric()` and the second when `pair[1].isalpha()`. When you find them add a `*` between them thus converting `2x` into `2*x`. – Ma0 Aug 26 '16 at 07:55

2 Answers2

3

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))
ewcz
  • 12,819
  • 1
  • 25
  • 47
0

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
Bruce
  • 7,094
  • 1
  • 25
  • 42