1833767 Members
2398 Online
110063 Solutions
New Discussion

sprintf in c compiles

 
Ted Mims
Occasional Advisor

sprintf in c compiles

I am experiencing some differences in output for sprintf for code compiled in 10.20 and 11.0.

sprintf(xxx, "%.2lf",doublefield);

when doublefield=0.735
obtains:

0.74 under 10.20
0.73 under 11.0
4 REPLIES 4
harry d brown jr
Honored Contributor

Re: sprintf in c compiles

You running 11/64?

live free or die
harry
Live Free or Die
A. Clay Stephenson
Acclaimed Contributor

Re: sprintf in c compiles

Hi Ted:

Welcome to floating-point math; I'm sure that you are aware either value is equally correct but in most cases you want to round up. Anytime, I'm doing any floating-point stuff, I assume this is going to happen and allow for it.

Typically, you want to add a small bias to the value before rounding.

e.g.

#define X_BIAS 0.0050000001

sprintf(xxx,"%.2lf",doublefield + X_BIAS);

Obviously it's a bit more complicated because you also need to handle negative amount so that generally a function is in order.

BTW: NEVER,EVER compare floating points for equality but rather do something like this:

if (atof(x - y) <= X_BIAS))
printf("x equals y");
else printf ("x not equal to y");

Regards, Clay
If it ain't broke, I can fix that.
harry d brown jr
Honored Contributor

Re: sprintf in c compiles

of course if you do this, you get your desired results:

#include

main()
{
float doublefield = 0.735;
printf("%.2lf",doublefield);
exit(0);
}


Clay,

Years ago I had to calculate what was deemed to be "close enough" (for a banking app), and of course that required me to learn Logarithms AGAIN! YUCK!!!!



live free or die
harry
Live Free or Die
A. Clay Stephenson
Acclaimed Contributor

Re: sprintf in c compiles

Hi Again Ted:

I'm an idiot. In my equality test I should have used fabs() rather than atof().

if (fabs(x - y) <= X_BIAS))
printf("x equals y");
else printf ("x not equal to y");

In any event, you really need to use the bias method because you are probably also going to see this problem (feature?) if you need to port your code to another platform/OS. Anytime you are doing floating-point calculations, you simply must take this feature into account.




If it ain't broke, I can fix that.