Skip to content

Instantly share code, notes, and snippets.

@a2gs
Last active March 3, 2019 04:46
Show Gist options
  • Save a2gs/22a9adef741af9d8ca72acdf428018dc to your computer and use it in GitHub Desktop.
Save a2gs/22a9adef741af9d8ca72acdf428018dc to your computer and use it in GitHub Desktop.
Floating-point error
#include <stdio.h>
int main(int argc, char *argv[])
{
double x = 516.80, y = 0;
long resp1 = 0, resp2 = 0;
resp1 =(long) (x * 100.0);
y = x * 100.0;
resp2 = (long)y;
printf("x[%f] y[%f] resp1[%ld] resp2[%ld] [%f]\n", x, y, resp1, resp2, (x * 100.0));
return(0);
}
@a2gs
Copy link
Author

a2gs commented Mar 2, 2019

See: trunc(3) / lrint(3) / round(3) / modf(3) / frexp(3)

trunc, truncf, truncl - round to integer, toward zero
lrint, lrintf, lrintl, llrint, llrintf, llrintl - round to nearest integer
round, roundf, roundl - round to nearest integer, away from zero

modf, modff, modfl - extract signed integral and fractional values from floating-point number
frexp, frexpf, frexpl - convert floating-point number to fractional and integral components

#include <math.h> and -lm

@a2gs
Copy link
Author

a2gs commented Mar 2, 2019

#include <stdio.h>
#include <math.h>

int main(int argc, char *argv[])
{
    double x = 516.80, y = 0.0, z1 = 0.0, z2 = 0.0;
    long k = 0;

    y = x * 100.0;
    k = lrint(y);
    z1 = ((double)k)/100.0;
    z2 = y/100.0;

    /* Untold truths (thanks to Pedro Castilho):
    printf("x[%.15f] * 100 = [%ld or %.15f]\nReturned to float: [%.15f or %.15f]\n", x, k, y, z1, z2);
    */
    printf("x[%f] * 100 = [%ld or %f]\nReturned to float: [%f or %f]\n", x, k, y, z1, z2);
    return(0);
}

cc -o floatError floatError.c -std=c11 -D_XOPEN_SOURCE=700 -D_POSIX_C_SOURCE=200809L -D_POSIX_SOURCE=1 -D_DEFAULT_SOURCE=1 -D_GNU_SOURCE=1 -lm

Output:
x[516.800000] * 100 = [51680 or 51680.000000]
Returned to float: [516.800000 or 516.800000]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment