TheNickqq - 1 year ago 100

Python Question

I'm trying to write a program as an exercise to calculate the integral value from a to b with one of 2 mathematical functions. My function integrate should have f as the mathematical function to integrate.

`from math import *`

def g(x):

return float(x) * float(x) + 3

def h(x):

return math.cos(float(x) * float(x))

def integrate(f, a, b, n):

H = (abs(float(a) - float(b)))/float(n)

ans = 0

xWaarde = a - H/2

print xWaarde

for k in range(1, n+1):

xWaarde = xWaarde + H

ans = ans + f(xWaarde) * H

return ans

print 'available functions:'

print 'g(x) = x^2+3'

while True:

print 'h(x) = cos(x^2)'

aIn = float(raw_input('integral from a = '))

bIn = float(raw_input('to b = '))

nIn = int(raw_input('Number of subintervals: '))

while True:

funcIn = raw_input('Which function do you want to use? (g or h): ')

if funcIn == 'g':

integrate(g,aIn,bIn,nIn)

break

elif funcIn == 'h':

integrate(h,aIn,bIn,nIn)

break

else:

print 'This function is not available'

print 'The definite integral is', integrate(funcIn, aIn, bIn, nIn)

doorg = raw_input('Do you want to continue? (y or n): ')

if doorg == 'n':

break

else:

The full Traceback is as follows:

`Traceback (most recent call last):`

File "C:/Users/Nick van Stijn/Desktop/Python/Assignment 3.1.py", line 38, in <module>

print 'The definite integral is', integrate(funcIn, aIn, bIn, nIn)

File "C:/Users/Nick van Stijn/Desktop/Python/Assignment 3.1.py", line 16, in integrate

ans = ans + f(xWaarde) * H

TypeError: 'str' object is not callable

EDIT: SOLVED

I made a mistake by calling a function at a time I didn't have to call it at all.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

The problem is that you call `integrate`

using the proper function, `f`

or `g`

, but then *discard* the result and instead call `integrate`

*again* for the print, this time passing just the *name* of the function, `funcIn`

.

Instead, you should just store the result in a variable, e.g., like this:

```
result = None
while result is None:
funcIn = raw_input('Which function do you want to use? (g or h): ')
if funcIn == 'g':
result = integrate(g,aIn,bIn,nIn)
elif funcIn == 'h':
result = integrate(h,aIn,bIn,nIn)
else:
print 'This function is not available'
print 'The definite integral is', result
```

Also, you could use a `dict`

to map function names to actual functions, instead of using a possibly large number of `if/elif/else`

:

```
functions = {'h': h, 'g': g}
while result is None:
funcIn = raw_input('Which function do you want to use? (g or h): ')
if funcIn in functions:
result = integrate(functions[funcIn],aIn,bIn,nIn)
else:
print 'This function is not available'
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**