当前位置:网站首页>Accuracy of BigDecimal Division
Accuracy of BigDecimal Division
2022-07-05 17:34:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
BigDecimal The accuracy of division
In the use of BigDecimal Division time , Encounter a ghost animal problem , The accuracy of this calculation , Result use return 0, Of course, I finally found that my posture was wrong , So record , Avoid repeating the mistakes later
I. Ask questions
In the use of BigDecimal When doing high-precision Division , I encountered a small problem when I didn't pay attention , as follows
@Test
public void testBigDecimal() {
BigDecimal origin = new BigDecimal(541253);
BigDecimal now = new BigDecimal(12389431);
BigDecimal val = origin.divide(now, RoundingMode.HALF_UP);
System.out.println(val);
origin = new BigDecimal(541253);
now = new BigDecimal(12389431.3);
val = origin.divide(now, RoundingMode.HALF_UP);
System.out.println(val);
origin = new BigDecimal(541253.4);
now = new BigDecimal(12389431);
val = origin.divide(now, RoundingMode.HALF_UP);
System.out.println(val);
}
Copy code What is the output above ?
0
0
0.043686703610520937021487456961257
Copy code Why are the first two 0 Well , If it's directly 541253 / 12389431 = 0 It's understandable , however BigDecimal Isn't it a high-precision calculation , To be reasonable, there should not be such a problem of division
We know that BigDecimal When triggering , You can specify parameters to keep decimals , If you add this , Will it be different ?
BigDecimal origin = new BigDecimal(541253);
BigDecimal now = new BigDecimal(12389431);
BigDecimal val = origin.divide(now, 5, RoundingMode.HALF_UP);
System.out.println(val);
Copy code The output is :
0.04369
Copy code So after the decimal point is specified , No problem , So make a bold guess , Is it some of the above case in , because scale When the value is not specified , The default values are different , Which leads to different accuracy of the final result ?
Simple in-depth source code analysis , The way of execution is origin.divide(now, RoundingMode.HALF_UP);, So this scale Parameters are aimed origin object , And this object , We can only analyze its structure , Because there is no other place to use
II. Source location
1. Shaping parameter transmission structure
Analyze the following line , Go straight to source
BigDecimal origin = new BigDecimal(541253);
Copy code The obvious int Pass parameter structure , Go in and have a brief look
// java.math.BigDecimal#BigDecimal(int)
public BigDecimal(int val) {
this.intCompact = val;
this.scale = 0;
this.intVal = null;
}
public BigDecimal(long val) {
this.intCompact = val;
this.intVal = (val == INFLATED) ? INFLATED_BIGINT : null;
this.scale = 0;
}
Copy code so, Clearly know the default scale by 0, That is to say, when origin Positive number , Division with it , Unrealistic designation scale When parameters are , The final returns are all without decimals , Take the same look , also long The way of transmitting reference , BigInteger It's the same thing
2. Floating point parameter transfer
The next step is floating point scale The default value confirms , This structure is a little more complex than the previous one , Source code is not posted , Too long , I don't quite understand what I did , Directly in a more obscene way , Get into debug Pattern , Step by step
@Test
public void testBigDecimal() {
BigDecimal origin = new BigDecimal(541253.0);
BigDecimal now = new BigDecimal(12389431.1);
BigDecimal tmp = new BigDecimal(0.0);
}
Copy code according to debug Result , first ,scale by 0; the second scale by 29, Third scale by 0
3. String The ginseng
It's still a bunch of logic , Also use one-step debug Try... In a different way
@Test
public void testBigDecimal() {
BigDecimal origin = new BigDecimal("541253.0");
BigDecimal now = new BigDecimal("12389431.1");
BigDecimal t = new BigDecimal("0.0");
}
Copy code The top three scale All are 1
4. Summary
- about BigDecimal In Division , It is best to specify its scale Parameters , Or there might be a hole
- about BigDecimla Of scale The principle of initialization , Need to take a closer look BigDecimal How did it happen
II. other
1. A gray Blog: https://liuyueyi.github.io/hexblog
A grey personal blog , Keep a record of all the blogs in your study and work , Welcome to visit
2. Statement
Better to believe than to believe , What has been said , It's all in one family , Because of limited personal ability , There are inevitably omissions and mistakes , If found bug Or better advice , Welcome criticism and correction , Thank you very much
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/149837.html Link to the original text :https://javaforall.cn
边栏推荐
- Mysql5.6 parsing JSON strings (supporting complex nested formats)
- Ordinary programmers look at the code, and top programmers look at the trend
- Learn about MySQL transaction isolation level
- ternary operator
- mysql5.6解析JSON字符串方式(支持复杂的嵌套格式)
- 33:第三章:开发通行证服务:16:使用Redis缓存用户信息;(以减轻数据库的压力)
- Oracle recovery tools -- Oracle database recovery tool
- mysql如何使用JSON_EXTRACT()取json值
- 云安全日报220705:红帽PHP解释器发现执行任意代码漏洞,需要尽快升级
- 7 pratiques devops pour améliorer la performance des applications
猜你喜欢

查看自己电脑连接过的WiFi密码

提高應用程序性能的7個DevOps實踐

Beijing internal promotion | the machine learning group of Microsoft Research Asia recruits full-time researchers in nlp/ speech synthesis and other directions

Rider set the highlighted side of the selected word, remove the warning and suggest highlighting

c#图文混合,以二进制方式写入数据库

Compter le temps d'exécution du programme PHP et définir le temps d'exécution maximum de PHP

Which is more cost-effective, haqu K1 or haqu H1? Who is more worth starting with?

漏洞复现----48、Airflow dag中的命令注入(CVE-2020-11978)

Check the WiFi password connected to your computer

MySQL之知识点(六)
随机推荐
MySQL之知识点(七)
Cartoon: a bloody case caused by a math problem
ClickHouse(03)ClickHouse怎么安装和部署
CMake教程Step2(添加库)
ternary operator
winedt常用快捷键 修改快捷键latex编译按钮
ICML 2022 | meta proposes a robust multi-objective Bayesian optimization method to effectively deal with input noise
机器学习01:绪论
Judge whether a number is a prime number (prime number)
Error in compiling libssh2. OpenSSL cannot be found
Function sub file writing
Is it safe and reliable to open futures accounts on koufu.com? How to distinguish whether the platform is safe?
深入理解Redis内存淘汰策略
Flow characteristics of kitchen knife, ant sword, ice scorpion and Godzilla
統計php程序運行時間及設置PHP最長運行時間
一文了解MySQL事务隔离级别
Design of electronic clock based on 51 single chip microcomputer
CVPR 2022 best student paper: single image estimation object pose estimation in 3D space
stirring! 2022 open atom global open source summit registration is hot!
菜刀,蚁剑,冰蝎,哥斯拉的流量特征