O/P of Lagrange Polynomial
1 view (last 30 days)
Show older comments
I am writing a script for generating lagrange polynomial. I have a problem with output. please guide. why is the op looking weird.
%%modelling a lagrange polynomial
%%inputs to code will be node points and function value at nodes
%%output will be polynomials p1(x), p2(x), p3(x) and p4(x)
%%count of math operations for each polynomial
clc
d=input('Enter degree of Langragian Polynomial: ');
n = input('Enter the node count ');
N = input('enter nodes in [] bracket:-');
Fx = input('enter function value in [] bracket:-');
disp('Nodes:')
disp(N);
disp('Function values:')
disp(Fx);
syms x;
s=0;
for k=1:n;
Poly=Fx(k);
for j=1:n;
if j~=k
Poly=Poly*(x-N(j))/(N(k)-N(j));
end
end
s=s+Poly;
% digits(4);
% r = vpa(s);
% fplot(matlabFunction(r),[min(N),max(N)]);
% hold on;
% o = i^2;
% O = sprintf('Mathematical Operations required for P%d(x) is %d',i,o);
% disp(O);
end
fprintf('Polynomial is \n');
digits(4); %to restrict decimal form to 4 signi. digit
r=vpa(s); %to represent in decimal form
disp(s);
% figure(1);
% fplot(matlabFunction(s),[min(N),max(N)]);
% figure(2);
% ezplot(s,[min(N)-3,max(N)+3]);
output
Enter degree of Langragian Polynomial: 4
Enter the node count 5
enter nodes in [] bracket:-[4 5 6 7 8]
enter function value in [] bracket:-[2 2.23607 2.44949 2.64979 2.82843]
Nodes:
4 5 6 7 8
Function values:
2.0000 2.2361 2.4495 2.6498 2.8284
Polynomial is
(((3184529073510883*x)/4503599627370496 - 3184529073510883/1125899906842624)*(x - 5)*(x - 6)*(x - 7))/6 + ((2*x -
10)*(x - 6)*(x - 7)*(x - 8))/24 + (((2757880562811939*x)/2251799813685248 - 2757880562811939/562949953421312)*(x -
5)*(x - 7)*(x - 8))/2 - (((1258795502346793*x)/562949953421312 - 1258795502346793/140737488355328)*(x - 6)*(x - 7)*(x
- 8))/6 - ((x - 5)*(x - 6)*(x - 8)*((1988932209435011*x)/2251799813685248 - 1988932209435011/562949953421312))/2
>>
0 Comments
Answers (1)
nick
on 29 Dec 2023
Hi Shivam,
I understand from your query that you need help understanding why the displayed output of the Lagrange polynomial is in rational form rather than decimal form.
Kindly refer to the code snippet from the code you shared. To display the polynomial in decimal form, you should display “r” instead of “s”, as “s” is a symbolic expression that contains the coefficients in rational numbers.
fprintf('Polynomial is \n');
digits(4); %to restrict decimal form to 4 signi. Digit
r = vpa(s); %to represent in decimal form
disp(r); % here instead of ‘s’, as in the code shared by you, ‘r’ the decimal form should be displayed
Here is the obtained output of the code you shared:
Figure 1 Obtained Lagrange Polynomial
Hope this helps,
Regards,
Neelanshu
0 Comments
See Also
Categories
Find more on Polynomials in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!