Java float比double更为精确? [英] Java float is more precise than double?

查看:158
本文介绍了Java float比double更为精确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

class Main {
    public static void main (String[] args) {
        System.out.print("float: ");
        System.out.println(1.35f-0.00026f);
        System.out.print("double: ");
        System.out.println(1.35-0.00026);
    }
}

输出:

float: 1.34974
double: 1.3497400000000002

??? float得到了正确的答案,但double却从无处添加了额外的内容,为什么?

??? float got the right answer, but double is adding extra stuff from no where, Why??

难道不是应该比float更精确吗?

Isn't double supposed to be more precise than float?

推荐答案

浮点数为4字节宽,而双精度数为8字节宽.

A float is 4 bytes wide, whereas a double is 8 bytes wide.

检查每个计算机科学家应了解的浮点运算法则

当然,双精度数具有更高的精度,因此舍入误差也较小.

Surely the double has more precision so it has slightly less rounding error.

将无限多个实数压缩为有限数量的位 需要一个近似的表示.虽然有无限 许多整数,在大多数程序中,整数计算的结果可以 以32位存储.相反,在给定固定位数的情况下, 大多数用实数进行的计算都会产生 不能用那么多位来精确表示. 因此 浮点计算的结果通常必须按顺序四舍五入 使其恢复为有限表示形式.此舍入误差为 浮点计算的特征.

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.

附带说明:-

我建议您是否要使用精确的十进制值,然后使用java.math.BigDecimal

I would suggest if you want the exact decimal values then use java.math.BigDecimal

这篇关于Java float比double更为精确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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