# Q：浮点数溢出[复制]

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
``````

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.

``````sqrt(6.626070040e-34)
ans =
2.5741e-17
``````

``````sqrt(6.626070040e-340)
ans =
0
``````

``````sqrt(6.626070040e34)
ans =
2.5741e+17

sqrt(6.626070040e340)
ans =
Inf
``````

``````realmax('double') %//largest allowed double
ans =
1.7977e+308
realmin('double') %//smallest allowed double
ans =
2.2251e-308
``````

``````(realmax('double')-10).^2
ans =
Inf
``````

matlab  floating-point