Getting NaN while using the ratio of power and factorial
조회 수: 2 (최근 30일)
이전 댓글 표시
1
With the following piece of code, I get NaN
l=0;
lp=2;
d=200;
a2= ((-sqrt(d))^lp);
a3 =((-sqrt(d))^l);
sum1=0
for m=0:500
a1= ((2^m)*(d^m))/(factorial(m))
mul=a1*a2*a3;
sum1=sum1+mul;
end
Is there any way to modify the code to get rid of the issue?
댓글 수: 1
James Tursa
2022년 7월 13일
Cross posted on stackoverflow and answered there over 4 hours ago. If you had simply checked the answer there you could have saved yourself the trouble of posting here and getting essentially the same answer.
답변 (4개)
Steven Lord
2022년 7월 13일
m = 500;
d = 200;
The numerator and denominator of your expression (for sufficiently large m) both overflow to inf. Dividing infinity by infinity results in a NaN.
numerator = 2^m*d^m
denominator = factorial(m)
x = numerator / denominator
One potential approach to avoid this is to avoid explicitly computing 2^m, d^m, or factorial(m).
numeratorVector = repmat(2*d, 1, m); % prod(numeratorVector) would effectively give numerator
denominatorVector = 1:m; % prod(denominatorVector) would effectively give denominator
xVector = numeratorVector./denominatorVector;
format longg
x2 = prod(xVector)
Let's check symbolically.
numeratorSymbolic = sym(2*d)^m;
vpa(numeratorSymbolic) % Pretty big
denominatorSymbolic = factorial(sym(m));
vpa(denominatorSymbolic) % Also pretty big
x3 = vpa(numeratorSymbolic/denominatorSymbolic) % Big but not quite as big as above
You could be a little more sophisticated / clever if you wanted (preemptively cancelling out factors of 2 in numeratorVector by dividing even values in denominatorVector by 2.) Or you could keep track of x for each value of m then figure out what you need to multiply it by to get x for the next value of m.
댓글 수: 0
Benjamin Thompson
2022년 7월 13일
The factorial function output increases very fast as input increases. See "doc factorial" for details. The output is "inf" for input of 171 or larger.
댓글 수: 1
Steven Lord
2022년 7월 13일
But 400^m overflows for m > 118 so this whole expression becomes infinite or undefined beyond that point.
d = 200;
(2*d)^118
(2*d)^119
참고 항목
카테고리
Help Center 및 File Exchange에서 Debugging and Analysis에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!