This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Type casting problem


Yeah, I have it:
	-- casting ((double)cost) has no effect since cost is double
	-- being sure to do the whole calculation in doubles we can
		cast the operation (which isn't really needed)
	-- casting to (long) which is also done automatically is nice but
		also solves nothing. It will also not round our
		calculation simply truncate the result.
This reveals we need to add 0.5 to our calculation to get the rounding in
the right direction without destroying the integer result:

	iamount = cost*100+0.5  ---> iamount = 6 !

What have we learned ? -- Never think about double numbers as integral
quantities. Any floating point value is a value x+/-sigma with sigma is an
error which has a defined upper border for each floating point data type.
So we need to round each double into a long one if we want to raise sigma
to saved digits.

look at :
	printf( "Cost %.30lf", cost );
-->
	Cost 0.059999999999999997779553950750
	       01234567890123456		: 15 good digits or
							sigma=1e-15
which corresponds to the double mantissa with 52 bits and
2^52 about 4.5e15. Of course our processor tries its best :-)

CU INGO



On Wed, 6 Jun 2001, Kevin Shallow wrote:

> Hello all. I am having a bit a problem with type
> casting a double to a long. I am using gcc version
> 2.96 20000731 (Red Hat Linux 7.1 2.96-81), on an x86
> type processer.
>
> Here's the code:
>
> #include <stdio.h>
>
> int main(int argc, char *argv[])
> {
>     double  amount;
>     double  cost;
>     long    iamount;
>
>     cost = 0.06;
>     amount = cost * 100;
>     iamount = (long)(((double)cost) * 100);
>
>     printf("Amount %lf\n", amount);
>     printf("Integer Amount %ld\n", iamount);
>
>     return (0);
> }
>
> Here's the output:
>
> Amount 6.000000
> Integer Amount 5
>
>
> There should be no difference between the 2 numbers,
> but the type cast seems to be losing some presision
> somewhere. Any help or tips would be greatly
> appeciated.
>
> Thanks,
>
> _Kevin
>
>
> __________________________________________________
> Do You Yahoo!?
> Get personalized email addresses from Yahoo! Mail - only $35
> a year!  http://personal.mail.yahoo.com/
>


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]