Skip to content

Instantly share code, notes, and snippets.

@fionn
Created May 22, 2017 22:46
Show Gist options
  • Save fionn/f1d524480962251acdba3c9e483dea1c to your computer and use it in GitHub Desktop.
Save fionn/f1d524480962251acdba3c9e483dea1c to your computer and use it in GitHub Desktop.
Comparison of derivatives of the sinc function
#include <iostream>
#include <cmath>
using namespace std;
double f(double x)
{
if(x == 0)
return 1;
return sin(x) / x;
}
double df(double x, double h = 0.0000001)
{
return (f(x + h) - f(x - h)) / (2 * h);
}
double dsinc(double x)
{
return -sin(x) / (x * x) + (1 / x) * cos(x);
}
int main()
{
for(double x = -13; x <= 13; x += 0.1)
cout << x << "\t" << f(x) << "\t" << df(x, 1) << "\t" << dsinc(x) << endl;
return 0;
}
TARGET = dsinc
all: $(TARGET)
$(TARGET): $(TARGET).cpp
g++ -Wall -Wextra -O2 $(TARGET).cpp -o $(TARGET)
.PHONY: tar
tar:
@tar -cvJf $(TARGET).tar.xz makefile $(TARGET).cpp
#!/usr/bin/gnuplot
set xtics pi
set format x '%.0Pπ'
set xrange [-5*pi:5*pi]
set xlabel "{/:Italic x}"
set grid
plot "sinc.dat" using 1:2 w lp title "sinc({/:Italic x})", "sinc.dat" using 1:3 w p title "numerical derivative, {/:Italic h} = 1", "sinc.dat" using 1:4 w l title "analytical derivative"
pause -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment