当前位置:网站首页>浮点数之间的等值判断
浮点数之间的等值判断
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
边栏推荐
- 微服务框架 Go-Micro 集成 Nacos 实战之服务注册与发现
- 谈谈敏捷开发概念和迭代开发方案
- Arthas install quick installation document
- 设置背景图片的两种方式,并解决手机端背景图片高度自适应问题
- 腾讯云服务器搭建wordpress网站的两种方式(详细图文新手版)
- 5 minutes get I use GitHub's five-year summary of these complaints!
- 低功耗蓝牙单芯片为物联网助力
- Installation and testing of Flink
- CCF BDCI hot topic: privacy information recognition in unstructured business text information
- I do digital transformation in traditional industries (1)
猜你喜欢

Arthas install quick installation document

帮助企业摆脱困境,名企归乡工程师:能成功全靠有它!

用微信表情翻译表白,程序员的小浪漫,赶紧Get起来!

你的钱为什么会被转走,这篇文章告诉你答案

SEO建设者,有哪些说不出的苦?

中国程序员 VS 日本程序员,满屏的羞羞!

超大折扣力度,云服务器 88 元秒杀

Openyurt in depth interpretation: how to build kubernetes native cloud edge efficient collaborative network?

echart 设置柱子之间的间距

Offline installation method of Arthas without network environment
随机推荐
Why is your money transferred? This article tells you the answer
瞧瞧,这样的『函数』才叫 Pythonic
AutoCAD2020 完整版安装图文教程、注册激活破解方法
jackson、fastjson、kryo、protostuff等序列化工具性能对比
The way of a million year salary Architect: on the architecture design of application system
MES系统在行业应用里区别于传统式管理
Android byte beat one side, was hanged by the interviewer! Fortunately, we got the offer from three sides
5分钟GET我使用Github 5 年总结的这些骚操作!
I heard that you changed your registered residence overnight. How can you help yourself if you work like ping?
【分享】接口测试如何在post请求中传递文件
Data consistency of cache
MES系统在行业应用里区别于传统式管理
如何使用Camtasia制作动态动画场景?
腾讯云服务器搭建wordpress网站的两种方式(详细图文新手版)
In depth analysis of the multi-user shopping mall system from search to create a profit point
Low power Bluetooth single chip helps Internet of things
Chinese programmer vs Japanese programmer, full screen shame!
CCF BDCI热门赛题:非结构化商业文本信息中隐私信息识别
What kind of experience does a doctor have when he turns his secret love brother into a husband?
国际顶刊Radiology发表华为云最新联合成果,AI辅助检测脑动脉瘤