Home > Software engineering >  How to put equation as an argument of function?
How to put equation as an argument of function?

Time:10-20

I would like to use the mathematical_operation as entry argument for function, so the user can enter any mathematical_operation to receive result. Was thinking that something like that might work with default arguments :

mathematical_operation = input()
def fun(a=1, b=1, c=1, mathematical_operation=a*(x**2) b*x c):
        x = np.linspace(-1,1,10)
        y = (lambda a,b,c: mathematical_operation)(a,b,c)
        print(x)
        print(y)
    return y
    
    fun(mathematical_operation = a*(x**2) b*x c)

However it gives error:

Traceback (most recent call last):
  File "C:\Users\Documents\Python\test.py", line 38, in <module>
    def fun(a = 1, b = 1, c = 1, equation = a*(x**2) b*x c):
NameError: name 'a' is not defined

CodePudding user response:

If you need more complicate evaluation of mathematical expressions/problems you should give a look at sympy, a 3-d party library for symbolic manipulations and more! It is more clean and safe than a string evaluation.

from sympy import symbols, lambdify
import numpy as np

def fun(a=1, b=1, c=1):
    a0, b0, c0 = symbols('a0 b0 c0')  # constant parameters
    x = symbols('x')  # variable
    expr = a0 * (x**2)   b0*x   c0  # expression
    expr = expr.subs(dict(a0=a, b0=b, c0=c))    # evaluation of the parameters
    func = lambdify(x, expr, 'numpy')   # function of x-only

    domain = np.linspace(-1,1, 10)
    y = func(domain)
    print(domain)
    print(y)
    return y

fun()

Output

[-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
  0.33333333  0.55555556  0.77777778  1.        ]
[1.         0.82716049 0.75308642 0.77777778 0.90123457 1.12345679
 1.44444444 1.86419753 2.38271605 3.        ]

Remark: the code seems a bit longer (and uglier!) just because I tried to respect the structure of the original code.

CodePudding user response:

Python thinks you are trying to pass a defined variable into the function. You could try eval:

import numpy as np


def fun(a=1, b=1, c=1, equation=None):
    x = np.linspace(-1,1,10)
    y = (lambda a,b,c,x: eval(equation))(a,b,c,x)
    print(x)
    print(y)
    return y

fun(equation = "a*(x**2) b*x c")
  • Related