How can I make a function in the lambda form accept a mapping regulation via input instead of explicitly stating it in the function?
Here is my code, I am trying to create a program for nummerical integration.
while True:
fx=input("Enter a function: ")
a=int(input("Choose lower integration limit: "))
b=int(input("Choose upper integration limit: "))
delta=float(input("Choose delta x: "))
step=int(1/delta)
interval=list(range((a*step),(b*step)))
f= lambda x: (x**2)*delta
Now I want to substitute this part
(x**2)
for an arbitray polynomial via the inputfx
result=map(f,interval)
print(sum(list(result))*(delta**2))
continue
if i try substituting (x**2)
for fx
it will produce this error:
Traceback (most recent call last):
File "C:\Users\Christian\Desktop\Python-Programme\Nummerische Integration.py", line 13, in <module>
print(sum(list(result))*(delta**2))
File "C:\Users\Christian\Desktop\Python-Programme\Nummerische Integration.py", line 11, in <lambda>
f= lambda x: fx*delta
TypeError: can't multiply sequence by non-int of type 'float'
*I am fully aware that this is probably not an optimal program for nummerical integration, the reason why im building this is just to exercise my programming skills while making programs that I still could theoreticaly use.
Disregarding of the question if this makes sense, the error comes from a type mismatch:
When you get the input from fx=input("Enter a function: ")
the variable fx will be of type str
. Try print(type(fx))
.
When you then perform fx*delta
you basically try to multiply a string with a numerical value, which does not make sense. Thus your Error TypeError: can't multiply sequence by non-int of type 'float'
.
A quick solution would be
while True:
n=int(input("Enter degree of polynomial: "))
print(type(fx))
a=int(input("Choose lower integration limit: "))
b=int(input("Choose upper integration limit: "))
delta=float(input("Choose delta x: "))
step=int(1/delta)
interval=list(range((a*step),(b*step)))
f= lambda x: (x**n)*delta
result=map(f,interval)
print(sum(list(result))*(delta**2))
continue
An advanced solution would need a way to parse your string input into a lambda function, which I think is not that easy.