Forum > General

Spurious real numbers

**Relativity**:

My program must calculate the average of two real numbers having each one digit after the comma (no more).

The result is always a number having at most 2 digits after the comma.

In principle I should get results like:

a := 123,1

b := 234,2

c := (a + b)/2 = 178,65

But often, instead of c=178,65 I get c=178,64999999999999 or c=178,65000000000001.

Sometimes I have to check whether 2 of the average numbers calculated this way are equal and I get of course that 178,64999999999999 is not equal to 178,65000000000001, although actually the difference is only due to this error and the numbers should be recognized as equal.

Is there any way to get clean results from simple operations like the one above ?

**eny**:

There is no absolute precision in real numbers.

Use rounded values or consider them equal if the difference is within a certain bandwidth.

Have a look here: https://www.youtube.com/watch?v=PZRI1IfStY0

**GetMem**:

There is a RoundTo function in the math unit.

**Relativity**:

Thanks a lot to eny and GetMem.

I used the RoundTo function and everything works fine now.

**Relativity**:

After some experimenting, I've come now to the conclusion that RoundTo is not the solution to the problem.

RoundTo is a function that rounds a real number to a given number of digits after the comma, so that, in principle, for example:

a := 2,3658;

b := RoundTo(a,-2);

-> b = 2,37

but the result number can still be affected by the said small error, so that you get something like, say:

-> b = 2,37000000000002

As I manage numbers with at most 2 digits after the comma, I find the best solution to make comparisons is something like:

if (Round(100*a) >= Round(100*b)) then

.....

I hope my experience can be useful to somebody in the future.

Navigation

[0] Message Index

[#] Next page