Writing a Taylor series function in matlab
37 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I want to write a MATLAB function that accepts three inputs (FUN, a, N), where FUN is an annonymous function, a is the point the taylor series is centered around and N is the order of the taylor series. I want the function to output the Nth order Taylor series for the function about a. I am new to matlab so still trying to understand its functionality
This is what I have so far:
function [TS] = tylorSeries(Fun,a.N)
4 commentaires
Réponses (2)
James Tursa
le 11 Mai 2018
You're close, but you need to pass in a function handle and then fix up a few other things in your code. So call the code like this:
taylorSeries(@(x)exp(x),0,10) <-- pass in a function handle as the first argument
Then you need to fix up these things:
The (x-a)*n should be a power, not a multiply, so it should be this instead:
(x-a)^n
You aren't summing up the terms. It should be accumulating, e.g.,
TS_Approx = TS_Approx + etc.
You aren't calculating or using the function derivatives properly. You should be calculating the derivative, and then evaluating that derivative at the point "a". E.g.,
derivative = Fun(x);
for n = 1:N
derivative = diff(derivative);
TS_Approx = TS_Approx + subs(derivative,a) * etc.
You need to fill in the etc part. Give it a shot and let us know if you still have problems.
0 commentaires
Jonah Schmidt
le 12 Mai 2021
This is the CLOSEST I've ever come to a working Taylor script: still having difficulties geting the correct answer, defeating the purpose of the script.
%Taylor Series Script%
clc;
clear variables;
close all;
disp('Clearing workspace, and closing tabs.')
format short;
disp('Now using Taylor Series expansion')
syms x;
%User Inputed Function%
z = input('Enter f(x) = ','s');
if isempty(z)
error('No function entered.')
end
f = inline(z);
%Order Input%
n = input('Enter the order of this Taylor series: ');
if isempty(n)
disp('No order entered, going to 7th order Taylor Expansion.')
n = 7;
end
%Step Size Input%
h = input('Enter the step size of this Taylor series (Usually 1): ');
if isempty(h)
error('No value entered.')
end
%Point Input%
p = input('Enter the point of which this Taylor series approximates: ');
if isempty(p)
error('No point entered.')
end
%Tag Line%
fprintf('\nOrder \t\t\t Value \t\t\t Approximate Error \n')
%xr = vpa(f(p)/factorial(n)*h^(n));%
%xr + (p.^n)./factorial(n)%
%Loop%
xr = p;
for iter = 1:n
xr = xr + vpa(f(p)/factorial(n)*h^(n));
v = func1(xr,n,p);
iter = iter + 1;
n = n + 1;
err = ((v-xr)/v)*100;
fprintf(' %d \t\t\t\t %f \t\t %f \n',iter-1,v,err)
end
%Line Break%
fprintf('\n')
%Function xr%
function a = func1(xr,n,p)
a = xr + (p.^n)./factorial(n);
end
0 commentaires
Voir également
Catégories
En savoir plus sur Numerical Integration and Differentiation dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!