user input string to function

Nico Vogeli nicco.9537 at gmail.com
Mon Dec 25 09:48:58 EST 2017


Am Montag, 25. Dezember 2017 14:51:21 UTC+1 schrieb Chris Angelico:
> 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

Hi Chris

Thanks very much for your quick response! 
I was in a bit of a rush, so I confused the variables (don't worry, I just messed arround to try different things, the original code was al tidy with the variable).

I tried your input, but now I get another error:


  File "C:/Users/Nicco ZHAW/Desktop/Test GUI/Test Projekt.py", line 42, in newton
    b = x - f(x)/fx(x)

TypeError: unsupported operand type(s) for /: 'function' and 'function'

This did not occure befor I tried to implement the user input..

Thank you very much!

Nicco



More information about the Python-list mailing list