且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java中具有快速性能的定点算法

更新时间:2023-02-26 18:17:12

您是否完全 确定BigDecimal是性能问题?您是否使用探查器来查找?如果是,那么两个可能有用的选项是:

Are you completely sure BigDecimal is the performance problem? Did you use a profiler to find out? If yes, two options that could help are:

1)使用 long 并将所有值乘以一个因子(例如,如果您对美分感兴趣,则为100).

1) Use long and multiply all values by a factor (for example 100 if you are interested in cents).

2)使用专门设计的类,该类实现与 BigDecimal 类似的东西,但在内部使用 long .我不知道是否存在一个好的开源库(也许 Java数学不动点库?).我很久以前(我相信是2001年)为J2ME编写了一个这样的类.正确一点有点棘手.请注意,除非需要高精度,否则 BigDecimal 也会在内部使用 long ,因此,在大多数情况下,该解决方案仅会有所帮助.

2) Use a specially designed class that implements something similar to BigDecimal, but using long internally. I don't know if a good open source library exists (maybe the Java Math Fixed Point Library?). I wrote one such class myself quite a long time ago (2001 I believe) for J2ME. It's a bit tricky to get right. Please note BigDecimal uses a long internally as well except if high precision is needed, so this solution will only help a tiny bit in most cases.

使用 double 并不是一个好的选择.

Using double isn't a good option in many cases, because of rounding and precision problems.