2

I have the following code but when it is run, it gives 0.0 It should return a value of 2 since I am attempting to integrate sin(x) in the interval [0, pi]. Please advise.

from math import sin, pi

def Rsum(a,b):
    for i in range(1001):
        s = 0
        delx = float((b-a)/1000)
        g = i*delx
        h = (i+1)*delx

        y_i = float(sin(a+g))
        y_ii = float(sin(a+h))
        s += 1/2 * (y_i + y_ii) * delx

    return s

print Rsum(0,pi)

2 Answers 2

4

1/2 is 0 in python 2.x. It is performing integer division and rounding down. You can get what you want by using 0.5 or 1.0/2 instead.

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

4 Comments

Thanks. Of course, rookie mistake. :) Using this, I get an answer (-4.93479408312e-06). However, this is not what is expected. The function is supposed to use the trapezoid rule to calculate the area under a curve, which in this case is sin(x). Any suggestions?
Try moving the s = 0 outside the loop.
Thanks recursive! This works now. :) I get 1.99999342027 However, how did this help exactly? In the previous case, was 's' being redefined (reset to 0) every time the loop was run?
@user2589188: Yes, exactly.
0

Try this:

from math import sin, pi

def Rsum(a,b):

    for i in range(1001):
        s = 0.0
        delx = float(b-a)/1000.0
        g = i*delx
        h = (i+1.0)*delx

        y_i = float(sin(a+g))
        y_ii = float(sin(a+h))
        s += 1.0/2.0 * (y_i + y_ii) * delx
        #s += 1/2 * (sin(a+i*delx) + sin(a+(i+1)*delx)) * delx

    return s

print Rsum(0,pi)

You should be careful about using integer values in floating point equations, if you have an integer, then convert it with float(). If you have a constant in your code like 10 then make it decimal... 10.0.

1 Comment

Thanks. Of course, rookie mistake. :) Using this, I get an answer (-4.93479408312e-06). However, this is not what is expected. The function is supposed to use the trapezoid rule to calculate the area under a curve, which in this case is sin(x). Any suggestions?

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.