Java run-off error(on float and double)

来源:互联网 发布:大数据魔镜 编辑:程序博客网 时间:2024/05/17 08:29

We can't store real 3.9 in Base 2.

double a = 3.9;boolean b = false;if(a == 3.9){   b = true;}System.out.println(b);

输出为:
false

(3.9)Base 10 = (1     1 .    1       1       1    00   1      1......)Base 2
      2^1 2^0 2^-1 2^-2 2^-3 ... 2^-6 2^-7 ...
    1/2    1/4   1/8      1/64 1/128
≈ 3 +0.8984375...
∴ We can not store real 3.9 in Base 2.

Example 1:
public class FloatingPointError {public static void main(String[] args) {double x = 3.9;double y = 3.8; double difference = x - y;System.out.println(difference);if (difference == 0.1) {System.out.println("I can do simple math.");} else {System.out.println("I am having trouble with easy problems.");}}}
输出为:
0.10000000000000009I am having trouble with easy problems.

我们可以通过“epsilon”(极小的正数)来检测是否x = 3.9。
Example 2:
public class FloatingPointDoneRight {public static void main(String[] args) {double EPSILON = 0.00000000001;double x = 3.9;double y = 3.8;double difference = x - y;if (Math.abs(difference - 0.1) < EPSILON) {System.out.println("I can do simple math.");} else {System.out.println("I am having trouble with easy problems.");}}}
输出为:
I can do simple math.




阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 发票联损坏怎么办 卷式专票的废票怎么办 大厅灯显旧怎么办 劳力士表面划痕怎么办 vivo升级不了怎么办 刷完机没备份怎么办 iphonex进水怎么办 手机进水怎么办啊 没网也没输入法怎么办 小米一直开关机怎么办 黄疸顽固怎么办 买手机没钱怎么办 没钱还想买手机怎么办 购买原始股骗局怎么办 一元购被骗怎么办 苹果蓝屏怎么办 文件管理打不开怎么办 青客宝已取消怎么办 大便时喷血怎么办 淘宝上买到假鞋怎么办 乐优炫彩中奖怎么办 黑色万斯鞋褪色怎么办 黑色vans掉色怎么办 vans后标掉漆怎么办 vans尾标掉了怎么办 匡威鞋磨脚怎么办 正品匡威开胶怎么办 实体店买到假鞋怎么办 脸上长闷包怎么办 微信卖鞋被骗了怎么办 鞋后跟脏了怎么办 欠了唯品会钱怎么办 好券提现密码不对怎么办 唯品币忘记密码怎么办 滴滴账号异常怎么办 滴滴换城市怎么办 招财猫注册号怎么办 华莱士会员卡怎么办 永旺微信会员卡怎么办 虎扑上买到假货怎么办 橡胶鞋磨脚怎么办