【问题标题】:Precision issue with Decimal.js tanDecimal.js tan 的精度问题
【发布时间】:2017-10-14 11:46:04
【问题描述】:

我一直在使用 Decimal.js 来提高我的函数的精度,该函数通过反复试验计算 a = tan(a) 的第 m 个正根。它可以工作,但是对于 nTan(504) 会返回“超出精度限制”错误(将返回 4.4934... 到 505 位)或更大。

var Decimal = require("decimal.js");
var fs = require("fs");

function nTan (acc, m) {
    var test = [1], acc = (parseInt(acc) || 15) + 1;
    Decimal.set({precision: acc});
    var n = new Decimal(fs.readFileSync("result.txt", "utf-8") || 4.4).toString();

    while (n.length + test.length - 2 < acc) {
        var dec = (new Decimal(n + test.join("")));
        if (dec.tan().cmp(n + test.join("")) >= 0) {
            test[test.length - 1]--;
            test.push(1);
        } else test[test.length - 1]++;

        if (test[test.length - 1] == 10) { test[test.length - 1] = 9; test.push(1); }
    }

    return (new Decimal(n + test.slice(0, -1).join(""))).plus(Math.PI * (parseInt(m) || 0)).toString();
}

我的问题是:

  1. 为什么 Decimal.js 在宣传最多 1e+9 位的容量时不计算过去的 504 位?
  2. 是否有替代节点或 JS API 可以更精确地支持该程序?

【问题讨论】:

  • 我不明白你的观点/问题。调用 nTan(504) 时,您将精度设置为 504 位。这里:Decimal.set({precision: acc})
  • 如果我调用 nTan(504) Decimal.js 会产生“超出精度限制”错误。任何小于该值的值(例如 nTan(250))都将按预期返回
  • 好的。当您超过 10 自然对数的内部存储字符串的长度时,函数getLn10 中会引发此错误。在存储库中,这是 1024 个字符。有没有可能,您使用的是旧版本的 lib,它存储了一个较短的字符串?
  • 错误表明它来自 Decimal.js 的 tan 函数:在 ...,在 nTan,在 Decimal.P.tangent.P.tan,在 Decimal.P.sine.P.sin,在 toLessThanHalfPi,在 getPi,在错误:[DecimalError] 超出精度限制

标签: javascript node.js math bignum decimal.js


【解决方案1】:

1000000000decimal.js precision 设置的最大允许值,但这并不意味着三角函数可以将结果返回到该有效位数.

三角法的精度限制是由源代码中Pi值的精度决定的。它在 decimal.js 文件中被硬编码为字符串变量 PI,精度为 1025 位。

这意味着 cossintan 方法的精度限制高达大约 1000 位,但实际数字取决于传递给他们的参数的精度。计算实际数字使用

ma​​ximum_result_precision = 1000 - argument_precision

例如,以下两者都可以正常工作

Decimal.set({precision: 991}).tan(123456789);

Decimal.set({precision: 9}).tan(991_digit_number);

因为,对于每一个,结果精度加上参数精度,即 991 + 99 + 991,小于或等于 1000。

这就是为什么当您尝试计算具有超过 500 位的参数的 tan 时程序会失败的原因,其精度超过 500 位数。

要做到这一点,需要 Pi 达到更高的精度 - 而这只能通过编辑 PI源代码,即添加更多数字。这些方法所花费的时间将成为限制因素。

我是图书馆的作者,我需要将其添加到其文档中。

【讨论】:

  • 谢谢,这很有意义。
猜你喜欢
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多