Skip to content

Instantly share code, notes, and snippets.

@unixpickle
Created April 27, 2017 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unixpickle/04d30144d86190562c4898261016e6a9 to your computer and use it in GitHub Desktop.
Save unixpickle/04d30144d86190562c4898261016e6a9 to your computer and use it in GitHub Desktop.
sin(x) power series
% Compute the power series of sin(x) using
% linear least-squares.
samples = 1000000;
degree = 10;
noise = 0.1;
xs = stdnormal_rnd(samples, 1);
xPowers = zeros(samples, degree);
for d = 1:degree
xPowers(:,d) = xs.^d;
end
target = sin(xs) + noise*stdnormal_rnd(samples, 1);
% Least squares regression.
actual = xPowers \ target
% Verify using the actual power series.
expected = zeros(degree, 1);
for i = 1:degree
if mod(i,2) == 1
expected(i) = 1/factorial(i);
if mod(i,4) != 1
expected(i) *= -1;
end
end
end
mse = mean((actual-expected).^2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment