0
import math

def g(x):
    return x**2+3

def Integrate(f, a , b, n):
    h=(b-a)/n
    result=0
    for k in range(n):
        x=k*h+h/2
        result+=f(x)*h
    return result

F=input("f:")
A=float(input("a:"))
B=float(input("b:"))
N=int(input("n:"))
print(Integrate(F, A, B, N))

Whenever i try to run this code, it reads F to be a string and gives an error when called in integrate(f, a, b, n). I found that there is no way in python to define F as a function, but calling a function in another function is definitely possible. Then how can i still pull this way of using an input to specify what function to use off?

error:

 line 14, in Integrate
    result+=f(x)*h
TypeError: 'str' object is not callable
  • @VasilisG. I'm pretty sure OP wants `f(x)`, to evaluate the function `f` at the point `x` in order to estimate the integral. – k_ssb Nov 21 '18 at 10:45
  • Could you provide some example input data for your problem? – Vasilis G. Nov 21 '18 at 10:47
  • probably quite tricky to do this securely, you'd need to write a parser. A *non-secure* way (NOT for external use) would be `exec(F)`, now if `input("f:")` was `F = lambda x: x * 2` you will have a working function – Chris_Rands Nov 21 '18 at 10:49

2 Answers2

0

You can input a function on the console by using a lambda (as a string), and use eval to convert the string to an actual function object. Your code would look like this:

F = eval(input("f:"))

On the console, if you want to integrate the function f(x) = 2 * x + 1, you'd input:

lambda x: 2 * x + 1

as a string. However, note that eval will execute (as Python code) whatever you input on the console, and this could be a security concern depending on how your program is used.

k_ssb
  • 6,024
  • 23
  • 47
-1

I don't know if you want to use function from math module, but if yes then you can obtain method from module by string like this:

function_to_call = getattr(math, f)
result += function_to_call(x) * h

When doing this you should surround with try except block to check if given function name exit in math module.

  • This only works if the function to integrate is defined in the `math` module. This would not work for an arbitrary function like `f(x) = 2*x`. – k_ssb Nov 21 '18 at 10:54