Welcome, Guest. Please login or register.

Author Topic: while() with float ?  (Read 3034 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline Piru

  • \' union select name,pwd--
  • Hero Member
  • *****
  • Join Date: Aug 2002
  • Posts: 6946
    • Show all replies
    • http://www.iki.fi/sintonen/
Re: while() with float ?
« on: February 17, 2006, 12:06:09 PM »
You can't use explicit == or != with floats/doubles since the float / double presentation might never actually match the comparision value. This is a fact you need to live with. It can be worked around by adding "precision" to the compare.

Example:
Code: [Select]
#include <stdio.h>
#include <math.h>

#define FCMP(a,b,p) (fabs((a) - (b)) < p)

int main(void)
{
  float aa = 0.0f;

  while(!FCMP(aa, 1.0, 0.001))
  {
    aa = aa + 0.01;
    printf(&quot;%f\n&quot;, aa);
  }

  return 0;
}


So instead of matching exact value, you are in fact matching some value range.

Making the type double won't help, nor having it work by luck on one particular system make it work on another processor family. Exact matching is a no-no.
 

Offline Piru

  • \' union select name,pwd--
  • Hero Member
  • *****
  • Join Date: Aug 2002
  • Posts: 6946
    • Show all replies
    • http://www.iki.fi/sintonen/
Re: while() with float ?
« Reply #1 on: February 17, 2006, 12:43:24 PM »
@ kas1e

[EDIT]Yes. Removed that brainfart. Sorry[/EDIT]

There is no speed difference. Macros have no speed penalty.

However, if you know specifics about the condition you're testing you can possibly remove fabs() (if you for example know that the subtraction result can't get negative). This fabs() stuff is there to make it generic and work when approaching from both below and above the target value.
 

Offline Piru

  • \' union select name,pwd--
  • Hero Member
  • *****
  • Join Date: Aug 2002
  • Posts: 6946
    • Show all replies
    • http://www.iki.fi/sintonen/
Re: while() with float ?
« Reply #2 on: February 17, 2006, 03:26:09 PM »
And here is a simple example to show how it can be handled using integers. The multiplier depends on the precision required (1000 is used here for clarity).

Code: [Select]

#include <stdio.h>

int main(void)
{
  int aa_i = 0 * 1000;

  while(aa_i != 1 * 1000)
  {
    float aa;

    aa_i = aa_i + 10; /* 0.0010 */
    aa = aa_i / 1000.0;

    printf(&quot;%f\n&quot;, aa);
  }

  return 0;
}