When writing code on demand today, it is occasionally found that when you set the variable type float and double calculations under Linux,
The results are not the same.
Requirement: Set value = Incoming Value * 10 * 122.88/1000;
Case: Set value = 1666*10*122.88/1000
= 2047.1808
When set to float, the code:
#include <stdio.h> #include <math.h>unsigned int fun (unsigned int sfn_threshold) { float f_sfn_ threshold; printf ("Input parameter=%d\n", sfn_threshold); F_sfn_threshold = (float) sfn_threshold*1.2288; printf ("F_sfn_threshold =%8lf\n", f_sfn_threshold); printf ("%.8lf\n", Fabs (F_sfn_threshold-(unsigned int) f_sfn_threshold)); return 0;} int main (int argc, char **argv) { unsigned int a=1666; unsigned int b=10000; unsigned int c=12888; unsigned int d=65535; Fun (a); return 0;}
Execution results (inconsistent with the results to be obtained):
[Email protected] test_float_compare]# gcc test_float_double_diff.c-o test_float_double_diff_1666[[email protected] Test_float_compare]#[[email protected] test_float_compare]#./test_float_double_diff_1666input PARAMETER=1666F_SFN _threshold = 2047.1807860.18078613[[email protected] test_float_compare]#
When set to double, the code:
#include <stdio.h> #include <math.h>unsigned int fun (unsigned int sfn_threshold) { double f_sfn_ threshold; printf ("Input parameter=%d\n", sfn_threshold); F_sfn_threshold = (double) sfn_threshold*1.2288; printf ("F_sfn_threshold =%8lf\n", f_sfn_threshold); printf ("%.8lf\n", Fabs (F_sfn_threshold-(unsigned int) f_sfn_threshold)); return 0;} int main (int argc, char **argv) { unsigned int a=1666; unsigned int b=10000; unsigned int c=12888; unsigned int d=65535; Fun (a); return 0;}
Execution Result:
[[Email protected] test_float_compare]#[[email protected] test_float_compare]#./test_float_double_diff_1666input Parameter=1666f_sfn_threshold = 2047.1808000.18080000[[email protected] test_float_compare]#
The difference between float and double accuracy in Linux