MarkN <> wrote:
Please don't top-post, thanks.
> "Eric Sosman" <> wrote in message
> news:...
>> MarkN wrote:
>> > modf() is a C Standard Library function
>> > double modf(double x, double* ip);
>> > returns fractional part and assigns to *ip integral part of x, both with
>> > same sign as x
>> > I have encountere a situation that has me a bit confused on the behaviot
> of
>> > this function.
>> >
>> > When calling the function with a value that DOES NOT have a fractional
>> > portion - the integral part is no always what is expected. I have seen
> this
>> > on two compilers - and compiler used for an Hitachi SH* processor and
>> > MSCVC6.00
>> >
>> > Here is a test program (MSVC6.00) that demonstrates the behavior:
>> >
>> > #include <math.h>
>> >
>> > void modftest(void)
>> > {
>> > double dblwhole;
>> > double dblValue = 0.000;
>> >
>> > for (int i = 0; i < 10000; i++)
>> > {
>> > modf(dblValue, &dblwhole);
>> > if((i%1000) == 0)
>> > {
>> > cout << dblValue << " " <<dblwhole << endl;
>> > //_beep(1200, 100);
>> > _sleep(1000);
>> > }
>> > dblValue += 0.001;
>> > }
>> > }
>> > Output:
>> > 1 1
>> > 2 1
>> > 3 2
>> > 4 3
>> > 5 5
>> > 6 6
>> > 7 7
>> > 8 8
>> > 9 9
>> >
>> > This is not the expected behavior: If you increase the loop count to
>> > 100,000, there are other occurences where the
>> > integer portion is 1 less than what it should be!
>> > I don't think this is correc behavior...
>> > Any thoughts?
>>
>> Thought the first: You're in the wrong newsgroup.
>> comp.lang.c++ is just down the hall, in that room where
>> four New Age bands and the Vienna Philharmonic are all
>> trying to play simultaneously.
>>
>> Thought the second: Your problem has nothing to do with
>> modf(), is not specific to C++ or to C, and has been seen
>> before. Frequently, in fact: it is Question 14.1 in the
>> comp.lang.c Frequently Asked Questions list
>>
>> http://www.eskimo.com/~scs/C-faq/top.html
>>
> I did in fact read 14.1 of FAQ. That would explain a problem in the
> fractional portion...
You don't print any "fractional part (which is the return value of
modf()), you just throw it away...
> This behavior "problem" is in the integer portion,
No, there isn't. Since 0.001 can't be expressed in binary without
losing some precision you sometimes will end up a little below
or above a "flat" number and the integral part of let's say
2.99999999999999999 is still 2 and not 3, as is 3.000000000001.
But if you print out the fractional and the integral part you
will see that their sums are always the expected numbers...
Regards, Jens
--
\ Jens Thoms Toerring ___
\__________________________
http://www.toerring.de