Extreme difference between the value of a function and the result in matlab
조회 수: 1 (최근 30일)
이전 댓글 표시
I tried to compute the value of the following function in matlab
format long
a=sqrt(4950000001);
b=30000;
y=333.75*b^6+a^2*(11*a^2*b^2-b^6-121*b^4-2)+5.5*b^8+a/(2*b);
fprintf("The value of y is: %f", y)
Output:
The value of y is: -590295810358705651712.000000>>
What confuses me, is that, if I try to compute the same value in Python for example or even with a normal calculator. The value is near 1.17, so far away from the output I get from matlab. I don't see why. Can anyone help? Did I maybe implement the function in a wrong way?
Note: I'm not sure which tags to add, so that this question is placed in the right place.
댓글 수: 0
답변 (2개)
Alan Stevens
2021년 3월 4일
Must hit an overflow. Express it as:
a=sqrt(4950000001);
b=30000;
r = (a/b)^2;
y1 = 333.75+r*(11*r - b^2 -121 - 2/b^4)+5.5*b^2 + r/(2*a*b^5);
y = b^6*y1;
and you get
y =
1.172603940074302
댓글 수: 0
Steven Lord
2021년 3월 4일
One of the terms in your expression involves b^8. For b = 30000 what is the value of that term?
b = 30000;
b8 = b^8
That value is large enough that the spacing between b8 and the next largest number that can be represented in MATLAB is quite large.
d = eps(b8)
(b8 + d) == b8 % false
(b8 + d/4) == b8 % true, and no this is NOT a bug
As an analogy, if you give Bill Gates a $20 bill it technically changes his net worth, but that amount of money is so small it's negligible and so for most practical purposes (like reporting in the media) his net worth doesn't change.
Now if you performed the calculations symbolically, we could represent those very large numbers exactly.
s8 = sym(b)^8
s8p1 = s8 + 1
logical((s8 + d/4) == s8) % false
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!