当前位置:网站首页>浮点数之间的等值判断
浮点数之间的等值判断
2020-11-09 16:06:00 【龘游戏人生龘】
(1) 指定一个误差范围,两个浮点数的差值在此范围之内,则认为是相等的。
float a = 1.0F - 0.9F;
float b = 0.9F - 0.8F;
float diff = 1e-6F;
if (Math.abs(a - b) < diff) {
System.out.println("true");
}
(2) 使用 BigDecimal 来定义值,再进行浮点数的运算操作。
BigDecimal a = new BigDecimal("1.0");
BigDecimal b = new BigDecimal("0.9");
BigDecimal c = new BigDecimal("0.8");
BigDecimal x = a.subtract(b);
BigDecimal y = b.subtract(c);
if (x.compareTo(y) == 0) {
System.out.println("true");
}
如上所示 BigDecimal 的等值比较应使用 compareTo()方法,而不是 equals()方法。
说明:equals()方法会比较值和精度(1.0 与 1.00 返回结果为 false),而 compareTo()则会忽略精度。
出自:Java开发手册(嵩山版)
版权声明
本文为[龘游戏人生龘]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/3628379/blog/4710132
边栏推荐
- 【亲测有效】Github无法访问或者访问速度的解决方案
- Rongyun has completed several hundred million RMB round D financing, and will continue to build global cloud communication capability
- Interview series 2: concurrent programming
- 5 minutes get I use GitHub's five-year summary of these complaints!
- cad教程 cad2016安装教程
- Two ways for Tencent cloud server to build WordPress website
- MES系统在行业应用里区别于传统式管理
- .NET报表生成器Stimulsoft Reports.Net 发布最新版v2020.5!
- Explore cache configuration of Android gradle plug-in
- 决策树算法-理论篇
猜你喜欢
Two ways for Tencent cloud server to build WordPress website
Do programmers pay too much to work overtime? Should programmer's salary be reduced? Netizen: let go of other hard pressed programmers
高质量的缺陷分析:让自己少写 bug
程序员过高工资导致加班?应该降低程序员工资?网友:放过其他苦逼的程序员吧
MES系统在行业应用里区别于传统式管理
使用Fastai开发和部署图像分类器应用
使用基于GAN的过采样技术提高非平衡COVID-19死亡率预测的模型准确性
深入探索 Android Gradle 插件的缓存配置
Embedded assembly in IOS
Guest interview: Wang Jian
随机推荐
Super discount, cloud server 88 yuan seconds
一款基于.NET Core的认证授权解决方案-葫芦藤1.0开源啦
华为云GaussDB:从颠覆自我到颠覆行业,重构数据库市场新格局
. net report builder stimulsoft Reports.Net Release the latest version of v2020.5!
最新版PyCharm 2020.3 :可实现结对编程,智能文本校对等|附下载体验
堆重启_uaf_hacknote
Simple use of AE (after effects)
如何使用Camtasia制作动态动画场景?
MES system plays an important role in the factory production management
Installation and testing of Flink
The worst hacker in history: stealing $1 billion of bitcoin without spending it for seven years, and finally being seized by the Department of justice
Data consistency of cache
Do programmers pay too much to work overtime? Should programmer's salary be reduced? Netizen: let go of other hard pressed programmers
同事笔记-小程序入坑点
国际顶刊Radiology发表华为云最新联合成果,AI辅助检测脑动脉瘤
What is website [new four modernizations]?
How to download and install autocad2020 in Chinese
Using GaN based oversampling technique to improve the accuracy of model for mortality prediction of unbalanced covid-19
Programmers before and after buying a house, after reading has cried blind
Native地图与Web融合技术的应用与实践