Results 1 to 4 of 4

Thread: floating point

  1. #1

    floating point

    hi
    consider this simple program

    Code:
    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 ?
    Last edited by AirPas; 23-09-2011 at 01:04 PM.

  2. #2
    This code is not allowed with floating points, it doesn't matter if it's 8 bytes or 4, there are always accuracy errors:
    Code:
    if car_pos = point_a then
    You can do it for example like this:
    Code:
    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:
    Code:
    if car_pos >= point_a then
    edit: I'll show what i mean by your code:
    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;
    Last edited by User137; 23-09-2011 at 02:27 PM.

  3. #3
    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"

  4. #4
    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 ==.
    Coders rule nr 1: Face ur bugz.. dont cage them with code, kill'em with ur cursor.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •