user input string to function

Nico Vogeli nicco.9537 at gmail.com
Mon Dec 25 08:36:16 EST 2017


Hi everybody. First ad foremost, happy Christmas!

I want to let the use input a function (like x**2) and parse it after that through code (for my numeric class)

import numpy as np
import matplotlib.pyplot as plt
import scipy.linalg
from sympy.abc import o, h
import sympy
from sympy import symbols
from scitools.StringFunction import StringFunction
from sympy.plotting import plot

x = symbols('x')
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
    
    
    a = x0
    k = 0
    
    while n > k:
        k += 1    
        b = a - f(a)/fx(a)
        print('x', k, '\n',b)
    
    print('Startwert -> x0', '\n', x0)
    print('Anzahl Iterationen', '\n', k)
    print('f(x~)', '\n', f(x))
    print('Näherungswert -> x~', '\n', b)

 
    return x0, k, f(x), x

(Please ignore all the input, they are used latter)

Now the output looks like this:

newton(2, 3*x**2, 6*x, 0.1, 2)
x 1 
 -x/2 + 2
x 2 
 -x/2 + 2
Startwert -> x0 
 2
Anzahl Iterationen 
 2
f(x~) 
 3*x**2
Näherungswert -> x~ 
 -x/2 + 2
Out[166]: (2, 2, 3*x**2, x)

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...

Regards

Nicco



More information about the Python-list mailing list