java 3 0.1_Why is 0.1 * 3 != 0.3 in Java? — oracle-tech

So, if I understood correctly, the problem was due to because 0.3 cannot be represented precisely? right?

No - the 0.1 is DECIMAL and, as I showed you, IT can not be represented precisely as a BINARY number no matter how many digits you use.How do you find such numbers?

It is the SAME for any base. If the value is NOT an exact multiple of the base then it can't be represented precisely. It is IS a multiple then it can.

DECIMAL is base ten. A number like 1/9 can't be represented because it becomes 0.11111... where the ONES continue indefinitely.

You generally do NOT need to 'find such numbers'. Most business work (except some scientific areas) have a limit to the number of decimal digits they need to preserve. So the values they use are generally rounded to that number of digits. They lost precision but the resulting number CAN BE compared to other values that have been treated the same way.like in above example, can I assume that 0.1 and 0.2 are precisely represented, which means 0.1 == 0.1?

You need to REREAD my reply and the example I provided.

I SHOWED YOU that the decimal value 0.1 is NOT precisely represented in binary.So ONE divided by TEN in base two becomes '0.00011001100110011001100110011001100110011001100110011...

See that? The series '0011' keeps repeating FOREVER.That Wiki link shows you the actual 'double' format - it stores a MAX of 52 bits for the fraction.

If the first 52 bits are the same then values will compare equally - otherwise they won't. Since 0.1 has the same 52 bits that 0.1 has they will compare equally as doubles.

Sorry, if I miss the point but this floating point comparison does look tricky to me.

IT IS TRICKY! But it isn't limited to binary values - the same problem exists for ANY base even decimal (base 10).

If you have a formula like '1/9 * 9' the result you get depends on the order you do the operations as well as the datatype you do them in.

Even in decimal '1/9' becomes '0.11111111111' where those '1's repeat forever. NOTHING in a computer repeats forever. So no matter where you stop it yo will LOSE PRECISION.

Let's say you decide to use only FIVE digits of precision. Then the value becomes '0.11111'. If you now multiply that by NINE you get '0.99999'.

NOTE: you do NOT get ONE! You can round the value to 1 if you want.

If you rearrange the formula to become '(9 * 1) / 9)' then you will get '9/9' which IS ONE without any rounding.

When you work with fractions, and division you have know those things and make sure your formulas and the order of calculation are done correctly for the datatypes you are using.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值