简体   繁体   English

在Javascript中使用Math.exp()和BigDecimal用于大浮点数

[英]Using Math.exp() in Javascript with BigDecimal for large floating point numbers

I'm attempting to perform the following calculation in Javascript: 我正在尝试在Javascript中执行以下计算:

e^x / (1 + e^x)

where x is a long floating point number. 其中x是一个长浮点数。

In this instance, I require accuracy to at least the 10th decimal place. 在这种情况下,我要求精度至少为小数点后十位。

I've been using BigDecimal to accurately handle the floating point numbers, as suggested at The Floating Point Guide . 我一直在使用BigDecimal来准确处理浮点数,正如“浮点指南”中所建议的那样。

My first attempt of: 我的第一次尝试:

var foo = new BigDecimal(myVeryLongFloatingPoint)
var bar = Math.exp(foo);
var spam = bar.divide(bar.add(new BigDecimal("1")));

led to the error (where xxxxx is the floating point number): 导致错误(其中xxxxx是浮点数):

TypeError: Object xxxxx has no method 'add'

So I attempted to tried convert bar into a BigDecimal object: 所以我试图将bar转换为BigDecimal对象:

var foo = new BigDecimal(myVeryLongFloatingPoint)
var bar = new BigDecimal(Math.exp(foo));
var spam = bar.divide(bar.add(new BigDecimal("1")));

which in turn leads to the error (where xxxxx is the floating point number): 这反过来导致错误(其中xxxxx是浮点数):

BigDecimal(): Not a number: xxxxx

Where am I going wrong? 我哪里错了?

Is this a sensible approach to handling this kind of calculation with floating points where a high degree of precision is required? 这是一种合理的方法来处理这种需要高精度浮点的计算吗?

您应该将字符串传递给BigDecimal

var bar = new BigDecimal(Math.exp(foo).toString());

There are a few mathematical approaches that might be useful. 有一些数学方法可能有用。 If x is positive and reasonably large, then you're taking the ratio of two large number and this will reduce your final precision. 如果x是正的并且相当大,那么你将采用两个大数的比率,这将降低你的最终精度。 Instead, you might: 相反,你可能会:

  1. Use 1./(1. + e^(-x)) instead. 请改用1./(1. + e^(-x))
  2. For large x, this is approximately 1.-e^(-x) , and the bigger x is, the better the approximation (eg, if x=100, then your error would be in the 86th digit). 对于大x,这大约是1.-e^(-x) ,并且x越大,近似越好(例如,如果x = 100,那么你的误差将在第86位)。

(Honestly, one should verify this before using it, I'm just going of off memory here an not writing anything down, but if this looks useful, I could grab a pencil...) (老实说,在使用它之前应该验证这一点,我只是在这里关闭内存而不是写下任何东西,但如果这看起来很有用,我可以抓一支铅笔...)

Math.exp only works on normal Numbers and cannot operate on BigDecimals. Math.exp仅适用于普通数字, 不能在BigDecimals上运行。 Math.exp is probably converting foo to NaN (or something like that) before continuing. 在继续之前,Math.exp可能会将foo转换为NaN(或类似的东西)。

You should look for an exponentiation method inside your BigDecimal class. 您应该在BigDecimal类中查找指数方法。 I looked at the source and I think there is a BigDecimal.pow method you could use instead. 我查看了源代码,我认为可以使用BigDecimal.pow方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM