Possible Loss of Precision
Say you have:
balance = balance + interestRate / 100.0 / 12.0 * balance;
Where balance is an int, and interestRate is a double. This will give a "possible loss of precision error." However say you're given:
balance += interestRate / 100.0 / 12.0 * balance;
This will not give output any warnings... my question is just "Why?"
Re: Possible Loss of Precision
Because the compiler is stupid?
Re: Possible Loss of Precision
Quote:
Originally Posted by CornedBee
Because the compiler is stupid?
Actually it's because the compiler is smart
the "+=" forces an implicit cast to (int)
Re: Possible Loss of Precision
That's exactly the reason why it should warn. Implicit casts from floating point to integral result in loss of precision that is not immediately obvious.
Re: Possible Loss of Precision
yes it is, considering you're manipulating an integer, you should know that the result will be an integer.
Re: Possible Loss of Precision
But you'd have to look up the declaration of the variable to know that it is an integer. And the declaration of the other variable to know that it's a float.
Besides, the warning should be on the implicit cast of the float, not the manipulation of the int.
Re: Possible Loss of Precision
CornedBee is right, this bug is being fixed in the 6th version of Java
Re: Possible Loss of Precision
Quote:
Originally Posted by ComputerJy
CornedBee is right, this bug is being fixed in the 6th version of Java
Even we say that this is a bug, is it helpfull in some situations, isn't it? Three four times I used this in my codes.
Re: Possible Loss of Precision
Quote:
Originally Posted by eranga262154
Even we say that this is a bug, is it helpfull in some situations, isn't it? Three four times I used this in my codes.
Even if they fixed it, you still can do this. You will only have to use explicit casting
Re: Possible Loss of Precision
Quote:
Originally Posted by ComputerJy
Even if they fixed it, you still can do this. You will only have to use explicit casting
It's true. Why did you say that "You will only have to use explicit casting"
Re: Possible Loss of Precision
Because the implicit casting is a bug that should be fixed
Re: Possible Loss of Precision
ComputerJy,
Can you explain how it becomes a bug. I thought it is reality of java and so I used it time to time.
Thanks.
Re: Possible Loss of Precision
Quote:
Originally Posted by eranga262154
ComputerJy,
Can you explain how it becomes a bug. I thought it is reality of java and so I used it time to time.
Thanks.
Because there is no way a compiler should make any changes to your code without notifying you