pow 使用带负指数的 Double 或 Decimal 返回不同的结果

And*_*dré 6 ios swift

使用 Xcode 11.1 如果我运行一个操场:

pow(10 as Double, -2)  // 0.01
Run Code Online (Sandbox Code Playgroud)

我使用 Float 得到相同的输出:

pow(10 as Float, -2) // 0.01
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试使用 pow(Decimal, Int) 如下所示:

pow(10 as Decimal, -2) // NaN
Run Code Online (Sandbox Code Playgroud)

有人知道为什么吗?

有没有更好的方法来处理 pow 和 Decimal 的正负指数?我需要十进制,因为它们的行为与我对货币价值的期望一样。

编辑:我知道如何从数学的角度解决这个问题,我想了解它为什么会发生和/或它是否可以在不增加我的代码的圈复杂度的情况下解决(例如检查指数是否为负并执行 1 /战俘)

use*_*632 6

嗯,从代数上来说,x^(-p) == 1/(x^(p))

因此,将负功率转换为正功率,然后取倒数。

1/pow(10 as Decimal, 2) // 0.01
Run Code Online (Sandbox Code Playgroud)


Car*_*rgo 2

我认为这个结构让我们对这个问题有了一个想法:

public struct Decimal {

    public var _exponent: Int32

    public var _length: UInt32 // length == 0 && isNegative -> NaN

    public var _isNegative: UInt32

    public var _isCompact: UInt32

    public var _reserved: UInt32

    public var _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)

    public init()

    public init(_exponent: Int32, _length: UInt32, _isNegative: UInt32, _isCompact: UInt32, _reserved: UInt32, _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16))
}
Run Code Online (Sandbox Code Playgroud)

长度条件应仅满足 length == 0,但由于 UInt32 不表示小数,因此满足条件...