I am having trouble understanding the following result:

Through[{IntegerPart,FractionalPart}[{100 4.02}]]
{{401}, {1.}}

Shouldn't it read {{402}, {0.}}?

I understand that in the Documentation one reads

"IntegerPart[x]+FractionalPart[x] is always exactly x. "

which is actually the case here, but one also reads:

"IntegerPart[x] in effect takes all digits to the left of the decimal point and drops the others. "

(emphasis added) which isn't the case here.

I was using IntegerPart[100#[[1]]]& as a second argument in GatherBy over a long list of entries where the first entry was a real number like 4.02 above.

It is actually the case that modifying the example produces the following

Through[{IntegerPart,FractionalPart}[{100 4.021}]]
{{402}, {0.1}}

Is this bug material or should this behavior be expected?

  • 1
    $\begingroup$ Have look at FullForm[100 4.02] and FullForm[Through[{IntegerPart, FractionalPart}[{100 4.02}]]]. The number 0.02 cannot be represented exactly in machine precision. $\endgroup$ – Henrik Schumacher Apr 14 '18 at 9:23
  • $\begingroup$ thanks for the hint! got it! $\endgroup$ – user42582 Apr 14 '18 at 9:27
  • 1
    $\begingroup$ You're welcome! $\endgroup$ – Henrik Schumacher Apr 14 '18 at 9:29
  • 1
    $\begingroup$ However, Through[{IntegerPart, FractionalPart}[{Rationalize@(100 4.02)}]] returns what you are expecting. I assume that Rationalize converts 0.02 to the rational number that when multiplied by 100 is an integer. $\endgroup$ – José Antonio Díaz Navas Apr 14 '18 at 13:48

As was kindly suggested by @Henrik Schumacher, 100 4.02 is not the same thing as 402, which is what I was assuming IntegerPart was seeing as input.

Taking FullForm[100 4.02] reveals that the input to IntegerPart evaluates to 401.99999999999994', which in turn-as should be expected-evaluates to {{401}, {1.}} by Through[{IntegerPart,FractionalPart}[{100 4.02}]].

So, the answer is, "no, the result is not a bug; instead IntegerPart operates exactly as it is expected to in the documentation. What appears as a discrepancy is due to the failure to realize how not all numbers can be represented exactly."

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.