【问题标题】:Getting the modulo of two real numbers with BCMath使用 BCMath 获得两个实数的模
【发布时间】:2018-03-22 00:45:16
【问题描述】:

我想知道一个实数是否是另一个实数的倍数。我正在使用 BC-Math,因为代码是进行价格计算的更大系统的一部分,并且由于浮点数学的行为,使用浮点数会导致多次计算的错误结果。

BC-Math 有bcmod() 来获取任意精度数的模数。但是,在 PHP 7.2 之前,此函数不适用于非整数数字字符串。例如:

echo bcmod('10', '9.2'); // 1, because '9.2' is truncated to '9'

将数字转换回浮点数并使用fmod() 不是一个选项,因为fmod function returning wrong result

我找不到任何解决方案,但我无法想象没有解决方案。

编辑:

以后遇到同样问题的读者你好!根据@chiliNUT 的回复,我为bcmath-extended 库创建了一个pull-request

【问题讨论】:

    标签: php bcmath


    【解决方案1】:

    我认为这可以通过一些数学来完成:

    您可以使用以下等式将mod(a,b)ab 关联起来:

    a = b * floor(a/b) + mod(a,b)
    

    (explanation)

    然后求解该方程以使 mod 产生

    mod(a,b) = a - b * floor(a/b)
    

    替换你得到的数字

    mod(10,9.2) = 10 - 9.2 * floor(10/9.2) = 0.8
    

    另请参阅此处了解 bcmath 楼层实施:How to ceil, floor and round bcmath numbers?

    【讨论】:

    • 我喜欢你的方法!但是,您的计算有错误。 mod(a,b) = a - b * floor(a/b) 而不是 mod(a,b) = a/b - b * floor(a/b)。你会更正你的答案以便我接受吗?
    猜你喜欢
    • 2013-07-22
    • 2013-04-19
    • 2012-10-10
    • 2011-02-13
    • 2020-02-19
    • 1970-01-01
    • 2011-03-24
    • 2017-08-28
    • 2014-09-16
    相关资源
    最近更新 更多