Java中的双重算术和等式 [英] double arithmetic and equality in Java

查看:105
本文介绍了Java中的双重算术和等式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个奇怪的(至少对我来说)。此例程打印真实:

  double x = 11.0; 
double y = 10.0;
if(xy == 1.0){
// print true
} else {
// print false
}

但是这个例程打印出错误:

  double x = 1.1; 
double y = 1.0;
if(xy == 0.1){
// print true
} else {
// print false
}

任何人都在意解释这里发生了什么?我猜这与 int 的整数运算有关,因为$ code> float s。此外,还有其他基础(除了 10 ),具有此属性?

解决方案

1.0有一个确切的二进制表示。 0.1不是。



也许你在问为什么0.1没有作为尾数存储为1,而指数为-10?但这不是它的工作原理。它不是十进制数加上指数,而是二进制数。所以10次不是一件自然的事情。



抱歉,也许最后一部分不清楚。最好把这个指数看作是一个位的移位。没有位的移位会将无限序列如0.1(十进制)转换成有限的一个。


Here's an oddity (to me, at least). This routine prints true:

double x = 11.0;
double y = 10.0;
if (x-y == 1.0) {
    // print true
} else {
    // print false
}

But this routine prints false:

double x = 1.1;
double y = 1.0;
if (x-y == 0.1) {
    // print true
} else {
    // print false
}

Anyone care to explain what's going on here? I'm guessing it has something to do with integer arithmetic for ints posing as floats. Also, are there other bases (other than 10) that have this property?

解决方案

1.0 has an exact binary representation. 0.1 does not.

perhaps you are asking why 0.1 is not stored as a mantissa of 1 and an exponent of -10? but that's not how it works. it's not a decimal number plus an exponent, but a binary number. so "times 10" is not a natural thing.

sorry, maybe the last part is unclear. it's better to think of the exponent as a shift of bits. no shift of bits will convert an infinite sequence like 0.1 (decimal) into a finite one.

这篇关于Java中的双重算术和等式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆