Math and physic in programing

184 views Asked by At

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?

2

There are 2 answers

21
Max 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 to 1.414213 for memory reasons. 1.414213 * 1.414213 = 1.99999840937 and not 2.

However, the square root of 4 is 2, and this can be stored in memory fully, without being cut off after a few decimal places. When you then do 2 * 2 you do get exactly 4.

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.

5
Charles Bretana On

sqrt generates floating point numbers. When using floats, on a computer, you cannot compare values and expect absolute equality. You must use a threshold difference comparison. floats are not used to count things, they are used to measure things, (to count things, use integers),. No two measured (even in the real world) values are ever exactly the same. they are only "close enough".

On a computer, it is impossible to represent every possible real number. SO every calculated value gets represented by the "closest" number in the set of possible numbers, (for that data type), that can be represented on the computer. This means that it is very slightly incorrect, and therefore after a few calculations, it will not conform to perfect equality comparisons.