简体   繁体   中英

How can I change my C program to give correct output for differentiation calculation?

I am trying to calculate the absolute error in the calculation of f'(1) (where f(x)=sin(x)) caused, due to direct calculation ie(cos(1)), and that done with the formula

f'(x) = (f(x+h)-f(x))/h  

ie Error function = cos(1) - ((sin(1+h)-sin(1))/h), for a small value of h.

But for a certain value of 'h' (say 10^{-8}), when I calculated through a very precise calculator( Kelsan Calculator ), the absolute error came to be 4.207355e-9 but computing the same thing using following program:

#include <stdio.h>
#include <math.h>
int main() {
  double h = 1e-8;
  double a = (sin(1 + h) - sin(1)) / h;
  printf("%10e", cos(1) - a);
}

I got 2.969885e-09. Is it possible to calculate this correctly on C?

Once you round two values which are extremely close to begin with and subtract the rounded values, the results are going to be all over the place.

Using a little trigonometry, you can represent the difference of two sines much more accurately.

double a = 2 * cos(1+h/2) * sin(h/2) / h;

This change results in printing exactly 4.207355e-09.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM