Help with basics and finite difference method

I have to write a program using the finite-difference formula to calculate the approximate value for the derivative of a function. The test will be tan(x) for x=1, determining the error by comparing with sec^2(x). I have no idea where to begin.

 采纳的回答

How about a for loop and taking the delta Y over the delta X where the separation is decreasing until it gets really really small, then compare to sec^2(x) and see how the difference gets smaller and smaller as the separation gets smaller and smaller. That's the finite difference method.

7 个评论

I'm supposed to use a log scale for the h (as in f(x+h)) and for the magnitude of error, would that get in the way of the for loop?
Thank you so much. I feel helpless.
So just start with h = 1, then go to h = 0.1, then to h = 0.01, then to h = 0.001, etc. You'll make h get smaller logarithmically.
x = 1;
for k = 1 : 6
h = 10^(1-k);
leftYValue = tan(x-h);
rightYValue = tan(x+h);
slope = ................
and so on.
Oh my god, I thought I was going to have to figure out how to actually implement f'(x) = (f(x+h)-f(x))/h. Numerical analysis is so foreign... sheesh. Well thank you so much, I appreciate it immensely.
Well that is what you're implementing. In my code, I went h above and h below the target x value (because I wanted to be symmetric), not just to one side like your equation, so my denominator would be 2*h rather than h. And my leftYValue is your f(x) and my rightYValue is your f(x+h). So the slope is (rightYValue - leftYValue)/(2*h), which is essentially your equation.
I see, that actually seems to be better than what is suggested by the instructor... I'll ask if I can try something like that. So I use that, and then compare by subtracting the slope from sec^2(x), and then plot the magnitude of error from that subtraction on one axis, and h on the other. That is so much better! Thank you!
OK, great, glad I could help. Can you go ahead and mark the answer as Accepted then?
I will, but I just talked to my instructor and he explained that though your method is valid, I must use the given formula. Could I just do the same things we talked about, only replace slope with
slope = (tan(x+h)-tan(x))/h
and do the error vs. h plot? I'm going to use loglog(h, error, -s), but this gives me a weird window... Please let me know if you can help with that as well, though I understand if you don't want to. Thanks for helping!

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Graphics Performance 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by