Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing floats. (Powerpc)

Tags:

c

powerpc

I am trying to print floats. Although variadic functions does not work with floats so they are promoted to double. I can manage to get rid of the warning by casting it to a double. While printing the results on some powerpc architecture, it gives incorrect value if printed with %f. Why ?

Test Code:

 #include <stdio.h>

 #define _echo_size(X) \
        printf ("Sizeof "#X" %u\n", sizeof(X))

int main (void)
{

        float x;
        long usec = 7L;

        _echo_size(float);
        _echo_size(double);
        _echo_size(short);
        _echo_size(int);
        _echo_size(long);
        _echo_size(long long);

        x = ((float) usec) / 2;
        printf("Expected: 3.5 Got: %1.1f\n", (double) x);
        printf("Expected: 3.5 Got: %1d.%.1d\n", (int)x,
                (int)((x-(int)x)*10));
        return 0;
}

X86 system result:

Sizeof float 4
Sizeof double 8
Sizeof short 2
Sizeof int 4
Sizeof long 8
Sizeof long long 8
Expected: 3.5 Got: 3.5
Expected: 3.5 Got: 3.5

ppc system result:

Sizeof float 4
Sizeof double 8
Sizeof short 2
Sizeof int 4
Sizeof long 4
Sizeof long long 8
Expected: 3.5 Got: 0.0  <--- Why this ?
Expected: 3.5 Got: 3.5

Is it a bug in the tool-chain ? otherwise what is the elegant way to print floats ?

like image 852
ededdy Avatar asked Jan 15 '13 14:01

ededdy


1 Answers

Oh, DUH! Your floating point value for x is being computed correctly, regardless of whether your FPU is doing it or if your compiler is doing it for you in software; it's just that your printf() implementation apparently doesn't treat %f as a double...

Are you on an embedded system with a custom printf() implementation? If so, it likely wasn't written to handle floating point numbers anyway, since floating point numbers often aren't even used in embedded systems, where programmers often opt to use integer variables & fixed point arithmetic, which is historically much much faster than floating point (and may still be on small embedded systems).

Or, another possibility: Your custom printf() is written to handle floating point numbers, but treats %f as a float, even though your compiler promotes float to double when passing it through .... Find your custom implementation & fix it to pull %f off the stack as a double instead of a float. (Your custom implementation may be getting a warning by trying to do that anyway, which people may have just been ignoring.) Search for va_arg(args,float) in that code and change it to va_arg(args,double). (Of course args in that example is my own variable name for a va_list; your variable name might be different.)

like image 99
phonetagger Avatar answered Dec 14 '22 13:12

phonetagger