Trapezoid Homework Read pages 201206 208210 of the text Turn

Trapezoid Homework Read pages 201-206, 208-210 of the text Turn in your Python code and a PDF file with your answer to #1, a discussion of your Due: Tuesday November 8 at 5:00 p.m results for #4, 5, and 6 I. Do exercises #2, 12, 14 on pages 214-215 2. Write a Python program to implement the Trapezoid Rule. Call your program trap and have it accept f, a, b,and n as input, where f is the name of the function, a and b are the endpoints of the interval in which the root lies, and n is the number of subintervals to be used. The pseudocode on page 204 of the text can provide some guidance if you are having trouble getting started. You should print out the final estimate of the integral 3. Test your program on the function in exercise #2 on page 214 which you computed by hand. Confirm you get the same answer. 4. Test your program on the integral in exercise #12 on page 214 with 10, 100, and 1000 subintervals. Explain why these computations illustrate that the trapezoid rule is 0(h2), where h is the length of each subinterval 5. Test your program on the integral in exercise #14 on page 214 using the value of n you found when you did the exercise and verify the error is less than 10-12. You can use Maple to compute the exact values or you can compute them by hand sin a 6. Test your program on the integral dx with 100 subintervals. What happens? Change your function so your program returns a correct estimate.

Solution

import math
def f(x):
    return 1.0/x;

def f2(x):
    return math.sin(x)


def trap(f, a, b, n):
    h = (a-b)*1.0/n;
    sum = 0.5*(f(a)+f(b))
    for i in range(1, n):
        x = a+i*h
        sum += f(x)
    sum = sum*h
    return sum

print trap(f, 1, 2, 3) #for problem 2
print trap(f2, -1, 2, 300) #for problem 12

#for problem 14 to find the number of n for given tolerance
correct_ans = 2
n = 100
while abs(trap(f2, 0, math.pi, n) - correct_ans)>pow(10, -12):
    n *= 10

print n
#n will be somewhere between 10^6 and 10^7

 Trapezoid Homework Read pages 201-206, 208-210 of the text Turn in your Python code and a PDF file with your answer to #1, a discussion of your Due: Tuesday No

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site