博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java之浮点运算
阅读量:4111 次
发布时间:2019-05-25

本文共 1157 字,大约阅读时间需要 3 分钟。

Java中的浮点数计算主要涉及float和double,他们都采用IEEE754标准,实际上是用利用科学计数法来表达实数。实数表示分为三个域: 

第一个域为符号域,0 表示数值为正数,而 1 则表示负数; 

第二个域为指数域,指数部分。其中单精度数为 8 位,双精度数为 11 位。float单精度的指数范围为-127 和 127 之间。 

第三个域为尾数域,其中单精度数为 23 位长,双精度数为 52 位长。

float用32bit存储,double用64bit存储。 double成为双精度:

double和float的区别:

1.double精度比较高,但是计算速度慢

2.原则是能用float的时候别用double

由于他们采用的是科学计数法来表述的,因此对计算要求比较高的地方不能采用直接double和float计算,建议采用BigDecimal,且必须用string去构造

举例如下:

public static void main(String[] args) {	BigDecimal b1 = new BigDecimal("0.9");	BigDecimal b2 = new BigDecimal("9");	System.out.println(b1.multiply(b2).toString());	double d1 = 0.9;	double d2 = 9;	System.out.println(d1 * d2);	float f1 = 0.9f;	float f2 = 9f;	System.out.println(f1 * f2);}

输出为:

8.18.18.099999

我们看到了float已经成无限接近了,但是满足不了需求。我们修改下测试case:

public static void main(String[] args) {	BigDecimal b1 = new BigDecimal("0.009");	BigDecimal b2 = new BigDecimal("9");	System.out.println(b1.multiply(b2).toString());	double d1 = 0.009;	double d2 = 9;	System.out.println(d1 * d2);	float f1 = 0.009f;	float f2 = 9f;	System.out.println(f1 * f2);}

输出结果变为:

0.0810.080999999999999990.081

double已经变成无限接近了

上述具体造成的原因查阅相关文档。

切记:

在计算的时候为了保证精度需要用BigDecimal,且需要用string的构造去构造

 

转载地址:http://wqqsi.baihongyu.com/

你可能感兴趣的文章
application/x-www-form-urlencoded、multipart/form-data、text/plain
查看>>
关于Content-Length
查看>>
WebRequest post读取源码
查看>>
使用TcpClient可避免HttpWebRequest的常见错误
查看>>
EntityFramework 学习之一 —— 模型概述与环境搭建 .
查看>>
C# 发HTTP请求
查看>>
初试visual studio2012的新型数据库LocalDB
查看>>
启动 LocalDB 和连接到 LocalDB
查看>>
Palindrome Number --回文整数
查看>>
Reverse Integer--反转整数
查看>>
Container With Most Water --装最多水的容器(重)
查看>>
Longest Common Prefix -最长公共前缀
查看>>
Letter Combinations of a Phone Number
查看>>
Single Number II --出现一次的数(重)
查看>>
Valid Parentheses --括号匹配
查看>>
Generate Parentheses--生成匹配括号(重)
查看>>
Remove Element--原地移除重复元素
查看>>
Remove Duplicates from Sorted Array--从有序数组中移除重复元素
查看>>
Count and Say
查看>>
Gas Station
查看>>