Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: [Win32, C, and way OT] C floats, doubles, and their equivalence

by creamygoodness (Curate)
on Jul 18, 2009 at 16:32 UTC ( #781353=note: print w/ replies, xml ) Need Help??


in reply to [Win32, C, and way OT] C floats, doubles, and their equivalence

Seems like the conversion glitch could be happening at several places.

Maybe the initial assignment of float foo needs a cast. MSVC warns about loss of precision in such cases -- maybe it's serious. :)

float foo = (float)nv;

As a workaround, perhaps you could truncate the initial assignment of the double:

double nv = (float)(2.0 / 3);

Lastly, maybe something is awry in the conversions that are being done during the comparison -- like it's ignoring your cast. It's a stab in the dark, but maybe a hack like this would get it to pay attention:

static __inline int compare_truncated_double_to_float(double d, float f) { float truncted_double = (float)d; if (f == truncated_double) { return 1; } else { return 0; } }

PS: This is relevant to the work I do ensuring Windows compatibility for my XS distros.

--
Marvin Humphrey


Comment on Re: [Win32, C, and way OT] C floats, doubles, and their equivalence
Select or Download Code
Re^2: [Win32, C, and way OT] C floats, doubles, and their equivalence
by syphilis (Canon) on Jul 19, 2009 at 00:12 UTC
    It's a stab in the dark ...

    Good stab - I can make use of that. The following outputs "True False" on the buggy compilers (and "True True" on sane compilers):
    #include <stdio.h> int main(void) { double nv = 2.0 / 3; float foo = 2.0 / 3; float truncated = (float)nv; if(foo == truncated) printf("True "); else printf("False "); if(foo == (float)nv) printf("True\n"); else printf("False\n"); return 0; }
    I can apply that method (used to obtain that "True") to PDL, which solves the problem I have asked about. Unfortunately, while it enables me to get the behaviour I want with my C demo scripts, it's still not producing the correct result with PDL - but this is such a fickle bug. I'll have to play around with it some more.

    PS: This is relevant to the work I do ensuring Windows compatibility for my XS distros

    #if defined _MSC_VER && _MSC_VER < 1400 then expect weirdness if you start comparing floats with doubles.

    Thanks Marvin.

    Cheers,
    Rob

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://781353]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2015-07-06 04:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (70 votes), past polls