浮点数溢出 [英] Floating Point Number Overflow
问题描述
我必须创建一个函数,我需要平方值。我被告知,即使初始值不是太大或不是太小,值的平方可能仍会溢出(返回 inf
)或下溢(返回 0
),我需要弄清楚如何防止这种情况。
我的问题是我甚至不明白当数字本身不是太大时平方的数字会引起溢出。
我认为这可能不是太小的数字,例如 1/3
带有重复的十进制数,但是MATLAB只是把它转换成 0.3333
。
有人可以给我一个这样的数字的例子,或者解释什么样的数字会导致这种情况?
<对于下溢,让我们考虑普朗克常量:6.626070040e-34
sqrt(6.626070040e-34)
ans =
2.5741e-17
那显然不够小,
sqrt(6.626070040e-340)
ans =
0
$ c
有你的下溢。
溢出可以用同样的方法看出来,只是用大数:
sqrt(6.626070040e34)
ans =
2.5741e + 17
sqrt(6.626070040e340)
ans =
Inf
下溢意味着数字对于MATLAB来说太小了,溢出意味着它们对于MATLAB来说太大了
感谢@ bchardon这里是我的MATLAB R2012a 64位系统上的数字:
realmax('double')%//最大允许双倍
ans =
1.7977e + 308
realmin('double')%//允许最小双倍
ans =
2.2251e-308
现在我们知道最大的可能值是MATLAB可以处理的,让我们试着在它下面并将其平方:
$ $ $ $ $ $ $ $ $ $ $ $ $(realmax('double') - 10) 。^ 2
ans =
Inf
所以我们尝试平方这里( realmax('double') - 10
)是MATLAB允许的,但不是可以调和的。
I have to create a function where I need to square values. I am told that even if the initial value is not too big or is not too small, the value squared might still overflow (returns inf
) or underflow (returns 0
), and I need to figure out how to prevent that.
My problem is I do not even understand what numbers can cause an overflow when squared when the number itself is not too large.
I thought it might be for the not too small numbers, e.g. 1/3
with repeating decimal numbers, but MATLAB just turns that into 0.3333
.
Can someone give me an example of such a number or explain what kind of numbers would cause this?
For underflow, let's consider Planck's constant: 6.626070040e-34
sqrt(6.626070040e-34)
ans =
2.5741e-17
Well, that's apparently not small enough, let's go smaller:
sqrt(6.626070040e-340)
ans =
0
There's your underflow.
Overflow can be seen the same way, just use big numbers:
sqrt(6.626070040e34)
ans =
2.5741e+17
sqrt(6.626070040e340)
ans =
Inf
Underflow means the numbers are too small for MATLAB to handle, overflow means they are too big for MATLAB to handle.
Thanks to @obchardon here are the numbers on my MATLAB R2012a 64bits system:
realmax('double') %//largest allowed double
ans =
1.7977e+308
realmin('double') %//smallest allowed double
ans =
2.2251e-308
Now that we know what the largest possible value is that MATLAB can handle, let's try going below that and square it:
(realmax('double')-10).^2
ans =
Inf
so the number we tried to square here (realmax('double')-10
) is allowable by MATLAB, but not squarable.
这篇关于浮点数溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!