I have a inline function does a frequency to period conversion. The calculation precision has to be using type long, not type double. Otherwise, it may cause some rounding errors. The function then converts the result back to double. I was wondering in below code, which line would keep the calculation in type long. No matter the parameter bar is 100, 100.0 or 33.3333.
double foo(long bar)
{
return 1000000/bar;
return 1000000.0/bar;
return (long)1000000/bar;
return (long)1000000.0/bar;
}
I tried it myself, and the 4th line works. But just wondering the concept of type conversion in this case.
EDIT:
One of the error is 1000000/37038 = 26, not 26.9993.
This problem, as you posed it, doesn’t make sense.
baris of an integral type, so1000000/barwill surely be less than1000000, which can be represented exactly by adouble1, so there’s no way in which performing the calculation all in integral arithmetic can give better precision – actually, you will get integer division, that in this case is less precise for any value ofbar, since it will truncate the decimal part. The only way you can have a problem in alongtodoubleconversion here is inbarconversion todouble, but if it exceeds the range ofdoublethe final result of the division will be 0, as it would be anyway in integer arithmetic.Still:
performs a division between
longs: 1000000 is anintor along, depending on the platform,baris along; the first operand gets promoted to alongif necessary and then an integer division is performed.performs a division between
doubles:1000000.0is adoubleliteral, sobargets promoted todoublebefore the division.is equivalent to the first one: the cast has precedence over the division, and forces
1000000(which is either alongor anint) to be along;baris along, division betweenlongs is performed.is equivalent to the previous one:
1000000.0is adouble, but you cast it to alongand then integer division is performed.doubles (DBL_DIG) and at least10**37as representable power of ten before going out of range (DBL_MAX_10_EXP) (C99, annex E, ¶4).