change operators position increase computational cost
1 次查看(过去 30 天)
显示 更早的评论
Dear all,
I noticed a strange (to me) behavior in my code. I'm solving a system of ODEs using ODE15s. The following term 'prefac' is calculated many times, and I noticed that, if I used the first equation, the calculation is about half of the time faster than using the second equation (~450s VS. ~870s). The only difference is that the term ./T_c is moved from the end of the equation to the beginning. If, during the simulation, I display the difference between the two, the maximum I get is 8e-22. I used 'prefac' to calculate terms in the order of magnitude of 1e-3, and in fact the solution does not change, only the computational cost increase.
prefac = (Mmix_c./param.R) .* (param.eps_c(end,:,:)./param.tau_c(end,:,:)) .* (1-s_c) .* (5.21e-1) .* ((T_c./139.681).^1.823) ./ (T_c);
or
prefac = (1 ./ (T_c)) .* (Mmix_c./param.R) .* (param.eps_c(end,:,:)./param.tau_c(end,:,:)) .* (1-s_c) .* (5.21e-1) .* ((T_c./139.681).^1.823);
do you have some explanation for it?
regards
Mauri
0 个评论
采纳的回答
Walter Roberson
2011-6-25
You would probably get even better performance with
5.21e-1 .* Mmix_c ./ param.R ./ T_c .* ((T_c./139.681).^1.823) .* (1-s_c) .* (param.eps_c(end,:,:) ./ param.tau_c(end,:,:)) ;
That is, do your commutative operation on scalar constants first in the expression, and then do your operations on matrices. There is no point in dividing each element of the matrix result by T_c if the matrix is also being multiplied by a scalar: instead "fold" the division into the scalar so just one division is done and the new scalar is being used for the necessary multiplication.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Ordinary Differential Equations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!