I have one simple question.. I have this code:
program wtf;
var i:integer;
begin
for i:=1 to 20 do
if sqrt(i)*sqrt(i)<>i then writeln(i);
readln
end.
... it goes through the loop 20 times and for numbers from 1 to 20 and it checks if square root multiplied buy square root of same number is equal to that number. If we use mathematical rules this program should never have anything on output but .... I get this :
2
3
5
6
7
8
10
12
13
15
18
19
20
can sombody explain what is going on?
This is because of precision. The square root of a number that is not a perfect square will give an irrational number, which cannot be represented in memory properly using floating-point arithmetic.
Instead, the number gets truncated after some digits (in binary, but the concept is the same as in decimal).
The number is now very close to, but not quite, the square root of the original number. Squaring it will produce a number that is very close to the original, but not quite.
Imagine it like this, the square root of 2 is
1.4142135623........(etc.)
but it gets cut off to1.414213
for memory reasons.1.414213
*1.414213
=1.99999840937
and not2
.However, the square root of
4
is2
, and this can be stored in memory fully, without being cut off after a few decimal places. When you then do2
*2
you do get exactly4
.Sometimes the number might get cut off, but when squaring it is still close enough to produce the original value. This is why
11
does not show.