Created
April 27, 2017 00:16
-
-
Save unixpickle/04d30144d86190562c4898261016e6a9 to your computer and use it in GitHub Desktop.
sin(x) power series
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% 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