Re: problem with precision when reading from file

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 09/16/2010 01:38 PM, Anna Sidera wrote:
> 
> 
> ----- Original Message -----
> From: Tim Prince <n8tm@xxxxxxx>
> Date: Wednesday, September 15, 2010 6:07 pm
> Subject: Re: problem with precision when reading from file
> 
>>  On 9/15/2010 7:37 AM, Anna Sidera wrote:
>>> Hello,
>>>
>>> I wrote the following program:
>>>
>>>
>>>
>>> #include<stdio.h>
>>> #include<math.h>
>>> #include<stdlib.h>
>>> #include<time.h>
>>> #include<string.h>
>>>
>>> int main()
>>> {
>>>
>>> FILE *fp;
>>> fp = fopen("test.c", "r");
>>> if (fp == NULL){
>>>      printf("Error opening input file\n");
>>>      exit(1);
>>> }
>>>
>>> float var1, var2, var3;
>>>
>>> fscanf(fp,"%f",&var1);
>>> fscanf(fp,"%f",&var2);
>>> fscanf(fp,"%f",&var3);
>>>
>>> if (var1!=0.01) printf("var1 = %g\n",var1);
>>> if (var2!=5) printf("var2 = %g\n",var2);
>>> if (var3!=0.6) printf("var3 = %g\n",var3);
>>>
>>>
>>>
>>> Where test.c contains the following:
>>>
>>> 0.01
>>> 5
>>> 0.6
>>>
>>>
>>>
>>> When I run the program I get the following output:
>>>
>>> var1 = 0.01
>>> var3 = 0.6
>>>
>>>
>>>
>>> I expected to get no output. Can you explain what is the problem?
>>>
>>> Thanks,
>>> Anna
>> Did you mean to try
>>
>> if (var1!=0.01f) printf("var1 = %g\n",var1);
>> if (var3!=0.6f) printf("var3 = %g\n",var3);
>>
>> or possibly to convert var1 and var3 back to short char strings 
>> and compare those?
>>
>> 0.01 and 0.6 are constants of type double and will have typically 
>> 29 more bits precision in their
>>  conversion from decimal to binary representation than your 
>> conversions to type float.

> I wrote a program that uses some input parameters. The program
> should read the input parameters from a file. There are also some
> input parameters that are arguments to main. Is there a way to read
> the input parameters so that for example var1*var2 gives a value
> equal to 0.05?

No.

> What is the best way to read the input parameters?

0.05 is a double constant.  It has a different value from 0.05f.  Your
program reads floats, not doubles.

To see why the values are different, try this program:

#include <stdio.h>
int main()
{
  float f = 0.05;
  printf("%20.20f\n", f);
  printf("%20.20f\n", 0.05);
  return 0;
}

Andrew.


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux