将所有BigDecimal操作设置为一定的精度?

编程入门 行业动态 更新时间:2024-10-23 13:23:01
本文介绍了将所有BigDecimal操作设置为一定的精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的Java程序集中在高精度计算上,该计算必须精确到至少120个小数位.因此,程序中所有非整数都将由BigDecimals表示.

My Java program is centered around high precision calculations, which need to be accurate to at least 120 decimal places. Consequentially, all non-integer numbers will be represented by BigDecimals in the program.

显然,我需要为BigDecimals指定舍入的精度,以避免无限的十进制表达式等.目前,我发现在BigDecimal的每个实例化或数学运算中都必须指定准确性非常麻烦.

Obviously I need to specify the accuracy of the rounding for the BigDecimals, to avoid infinite decimal expressions etc. Currently, I find it a massive nuisance to have to specify the accuracy at every instantiation or mathematical operation of a BigDecimal.

是否可以为所有BigDecimal计算设置全局精度"?(例如python中的 Decimal 模块的 Context.prec())

Is there a way to set a 'global accuracy' for all BigDecimal calculations? (Such as the Context.prec() for the Decimal module in python)

谢谢

规格:Java jre7 SE Windows 7(32)

Specs: Java jre7 SE Windows 7 (32)

推荐答案

(几乎)原始

不是那么简单,但是您可以创建 MathContext 并将其传递给所有 BigDecimal 构造函数和执行操作的方法.

Not as simple, but you can create a MathContext and pass it to all your BigDecimal constructors and the methods performing operations.

修订版

或者,您可以扩展 BigDecimal 并通过提供正确的 MathContext 并使用 divide :

Alternatively, you can extend BigDecimal and override any operations you want to use by supplying the right MathContext, and using the rounding version of divide:

public class MyBigDecimal extends BigDecimal { private static MathContext context = new MathContext(120, RoundingMode.HALF_UP); public MyBigDecimal(String s) { super(s, context); } public MyBigDecimal(BigDecimal bd) { this(bd.toString()); // (Calls other constructor) } ... public MyBigDecimal divide( BigDecimal divisor ){ return new MyBigDecimal( super.divide( divisor, context ) ); } public MyBigDecimal add( BigDecimal augend ){ return new MyBigDecimal( super.add( augend ) ); } ... }

更多推荐

将所有BigDecimal操作设置为一定的精度?

本文发布于:2023-11-30 02:53:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648477.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:设置为   精度   操作   BigDecimal

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!