Write a (C++, Java, or Python) program to compute an approximate value for the d
ID: 3748142 • Letter: W
Question
Write a (C++, Java, or Python) program to compute an approximate value for the derivative of a function using the finite difference formula
f `(x) f(x + h) f(x) / h .
(2) Test your program using the function sin(x) for x = 1. Determine the error by comparing with the built-in function cos(x). Plot the magnitude of the error as a function of h, for h = 1/2 , 1/4 , 1/8 , . . . You should use a log scale for h and the magnitude of the error. Is there a minimum value for the magnitude of the error?
b) Check if the corresponding value of h to the minimum value for the magnitude of the error can be approximately equal to eps ? Why?
3. a) (10 points) write a program to compute an approximate value for the derivative of a function using the finite difference formula fiunction cos(x). Plot the magnitude of the error as a function of h, for hYon should use a log b)(5 points) Check if the corresponding value of h to the mini value for the maguitude of the error can be approximately equal to es Why?Explanation / Answer
Part A:
import math
import matplotlib.pyplot as plt
x = 1
h = []
err = []
for k in range(0,49):
h = h+[ 1/math.pow(2,k+1)]
df = (math.sin(x+h[k])-math.sin(x))/h[k]
err = err +[math.fabs(df-math.cos(x))]
fig, ax = plt.subplots()
ax.loglog(h,err)
plt.xlabel('h')
plt.ylabel('Err')
plt.show()
for k in range(0,49):
if err[k] == min(err):
H = h[k]
ApproxH = math.sqrt(math.fabs(3.0*(4.0/3.0-1.0)-1.0))*math.fabs(x)
print 'h corresponding to minumum error='
print H
print 'rule of thumb h ='
print ApproxH
Part B:
import math
import matplotlib.pyplot as plt
x = 1
h = []
err = []
for k in range(0,49):
h = h+[ 1/math.pow(2,k+1)]
df = (math.sin(x+h[k])-math.sin(x-h[k]))/(2*h[k])
err = err +[math.fabs(df-math.cos(x))]
fig, ax = plt.subplots()
ax.loglog(h,err)
plt.xlabel('h')
plt.ylabel('Err')
plt.show()
for k in range(0,49):
if err[k] == min(err):
H = h[k]
ApproxH = math.sqrt(math.fabs(3.0*(4.0/3.0-1.0)-1.0))*math.fabs(x)
print 'h corresponding to minumum error='
print H
print 'rule of thumb h ='
print ApproxH
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.