user input string to function

Chris Angelico rosuav at gmail.com
Mon Dec 25 08:50:48 EST 2017


On Tue, Dec 26, 2017 at 12:36 AM, Nico Vogeli <nicco.9537 at gmail.com> wrote:
> Hi everybody. First ad foremost, happy Christmas!

Same to you!

> I want to let the use input a function (like x**2) and parse it after that through code (for my numeric class)
>
> def newton(x0, s, s2, tol, n = 20000):
>     '''
>     Näherung zur lösung einer Gleichung mit dem Newton-Verfahren
>     x0 = Startwert
>     f = zu lösende Funktion
>     fx = Ableitung der Funktion
>
>     '''
>     def f(a):
>         y = s
>         return y
>
>     def fx(a):
>         y = s2
>         return y


> newton(2, 3*x**2, 6*x, 0.1, 2)
>
> I notice that the x is not converted to an integer, because of the x = symplos('x')
> But I don't know how I could possibli change the code to work...

The easiest way is to pass a *function* to newton(). It'd look like this:

def newton(x0, f, fx, tol, n=20000):
    ... as before, but without the nested functions

newton(2, lambda x: 3*x**2, lambda x: 6*x, 0.1, 2)

At least, I think that's how you're doing things. Inside the nested
functions, you use 'a', but outside, you use 'x'. Are those
representing the same concept? If so, the lambda functions given here
will have the same effect.

Hope that helps!

ChrisA



More information about the Python-list mailing list