Java中具有快速性能的定点算法 [英] fixed point arithmetics in java with fast performance

查看:43
本文介绍了Java中具有快速性能的定点算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用Java精确地表示一些数字,并在小数点后固定小数点的数量;在那个小数点之后,我不在乎.(更具体地说-金钱和百分比.)

I need to represent some numbers in Java with perfect precision and fixed number of decimal points after decimal point; after that decimal point, I don't care. (More concretely - money and percentages.)

我现在使用Java自己的BigDecimal,但是我发现,它 确实 很慢,并且开始在我的应用程序中显示.

I used Java's own BigDecimal now, but I found out, that it's really slow and it starts to show in my application.

所以我想用一个常规"整数和一个定点算术(长整数对于我的目的足够大的精度)来解决它.

So I want to solve it with a "regular" integers and a fixed-point arithmetics (long integers have big enough precision for my purposes).

现在,我想我不是第一个遇到这种问题的人,并且已经有一个针对该问题的库,该库已经实现了乘法/除法运算-但似乎不是.

Now, I would think that I am not the first one who has this kind of problem and there would be already a library for that, that already has multiplication/division implemented - but it seems that it isn't.

现在,我很可能可以自己写(也许我会写),但是,实际上,我真的是第一个需要它的人吗?还没有图书馆吗?

Now, I very probably can write it myself (and I probably will), but really, am I really the first person that needs this? Isn't there already some library for that?

推荐答案

您是否完全 确定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.

这篇关于Java中具有快速性能的定点算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆