Napisałem szybki programik
#include <iostream>
#include <math.h>
#include <fstream>
using namespace std;
double f(double x){
return sin(x);
}
double f_d(double x){
return cos(x);
}
double central(double x, double h){
return (f(x+h) - f(x-h)) / h * 0.5;
}
int main(){
double a = 0.0;
double b = 2.0 * M_PI;
double h = 0.01;
ofstream file;
file.open("result.txt");
for (double x = a; x <= b; x += h)
file << x << ", " << f_d(x) << ", " << central(x, h) << "\n";
file.close();
return 0;
}
wraz z gnuplotem
set term png
set output "result.png"
set xlabel "x"
set ylabel "sin'(x) = cos(x)"
set autoscale
plot "result.txt" using 1:2 w l lw 6 title "cos(x)", \
"result.txt" using 1:3 pt 7 ps 0.4 title "central"
Co nam daje wykres różnicy centralnej oraz dokładnego rozwiązania:
Wykresy pokrywają się, ale oczywiście jest błąd, którego gołym okiem nie widać.