PDA

View Full Version : floating point



AirPas
23-09-2011, 01:01 PM
hi
consider this simple program



program Project1;
{$APPTYPE CONSOLE}
const
car_speed = 0.01;
point_a = 5.14;
point_b = 10.00;
var
car_pos : single = 0.0;
begin

while True do
begin
car_pos := car_pos + car_speed;
writeln('car position :',car_pos:2:2);
if car_pos = point_a then
writeln('we are in point a');
if car_pos = point_b then
begin
writeln('we are in point b');
break;
end;
end;
readln;
end.

the problem is the 2 conditions (if) will never executing , but if i change car_pos from single to currency , the problem disappeared.

well i know this is because of floating point rounding problem , but currency is 8byte length , so if i want only 4byte real variable , what suggestion would you propose ?

User137
23-09-2011, 01:57 PM
This code is not allowed with floating points, it doesn't matter if it's 8 bytes or 4, there are always accuracy errors:

if car_pos = point_a then

You can do it for example like this:

if abs(car_pos - point_a)<0.001 then
But this is also extremely rarely used way...

Normally you should organize code so that you can check:

if car_pos >= point_a then

edit: I'll show what i mean by your code:


while True do begin
car_pos := car_pos + car_speed;
writeln('car position :',car_pos:2:2);
if car_pos >= point_b then begin
writeln('we are in point b');
break;
end else if car_pos >= point_a then
writeln('we are beyond point a, but before point_b');
end;

AirPas
23-09-2011, 03:55 PM
This code is not allowed with floating points
i would like to know if this is just with delphi or with all languages .

in c++ why this code work


float a = 0.01f;
float b = 0.01f;

if ( (a + b) == 0.02f)
printf("Equal \n");
else
printf("Not equal \n");

but in pascal will always print "Not equal"

chronozphere
23-09-2011, 03:59 PM
Can you prove to us that floating point comparison works like that in C++? My understanding is that floating point errors happen in every language and that you should always use < or > rather than ==.