0

I am having problem with the simpsons rule. It is saying float object cannot be interpreted as an integer in for i in range(1, (n/2) + 1):

def simpson(f, a, b, n):
h=(b-a)/n
k=0.0
x= a + h
for i in range(1, (n/2) + 1):
    k += 4*f(x)
    x += 2*h

x = a + 2*h
for i in range(1, n/2):
    k +=2*f(x)
    x += 2*h
return (h/3)*(f(a)+f(b)+k)

result=simpson(lambda x:x, 0, 1, 4) print (result)

1

1 Answer 1

0

n / 2 returns a float in Python 3, while range only works with integers. You need to use integer division (//):

range(1, (n // 2) + 1).

Sign up to request clarification or add additional context in comments.

3 Comments

Ok i will give it a try
It worked thank you. I used the second method. So can you explain me how this first one works. i mean do i have to import any function before using this because when i tried the first function its is saying that the floor function is not defined.
@PemaChidaSherpa Indeed, in order to use floor you need to import it: from math import floor. I removed it from my answer as it is easier to simply use //.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.