Why does evaluating a function with symbolic variables take so much longer than with a double?

8 ビュー (過去 30 日間)
I have a code (below) using the Secant Method to evaluate a function f(x) = exp(x) - 3*x^2 with p_0 = 3, p_1 = 5, and a tolerance of 1e-5. As is, the code runs exceedingly slow. It seems to get worse with each iteration, but if I replace lines 22, 24, and 41 with an evaluation of '= double(subs(g))', then it has a much, much faster turnaround time. What is happening when MATLAB tries to evaluate line 28 with a 1x1 sym that makes it so much slower?
%% Inputs
syms x;
fprintf(1,'Input the function g(x) in terms of x.\n');
fprintf(1,'For example: cos(x) \n');
s = input('');
g = @(x) s; %user-input function
fprintf(1,'Input the initial approximation to P0.\n');
p_0 = input(''); %initial approximation
fprintf(1,'Input the initial approximation to P1.\n');
p_1 = input(''); %initial approximation
fprintf(1,'Input the desired tolerance.\n');
tol = input(''); %allowable absolute error
fprintf(1,'Input the maximum iterations.\n');
n = input(''); %max iterations
i = 2; %initialize counting variable
x = p_0;
q_0 = subs(g);
x = p_1;
q_1 = subs(g);
%% Secant Method
while i <= n
p = p_1 - q_1*(p_1- p_0)/(q_1 - q_0);
tol_n = abs(p - p_1);
if tol_n < tol
fprintf(['p = %.8f after %d iterations with a tolerance of %.0e'...
',\nwhich is less than the specified tolerance of %e'], p,...
i, tol_n, tol);
return
else
i = i + 1;
p_0 = p_1;
q_0 = q_1;
p_1 = p;
x = p;
q_1 = subs(g);
end
end
%% Error
fprintf(['The method failed after %d iterations with a value of\n p'...
' = %.8f\nand a tolerance of %.8f\n'], i-1, p,tol_n);

採用された回答

Steve Eddins
Steve Eddins 2020 年 9 月 23 日
When MATLAB performs arithmetic on normal numeric values, which are represented internally as double-precision floating-point numbers, the arithmetic is performed directly on hardware -- the floating-point computation unit of your CPU core (or cores).
Symbolic computations performed via a symbolic math engine. Unlike the floating-point operations on your CPU, which are limited to a 64-bit representation, the symbolic math engine computes exact mathematical quantities, and it does so in a software layer.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeNumbers and Precision についてさらに検索

製品


リリース

R2017a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by