根据文档此处,Swift 3/4十进制类型是一种表示形式在以10为基数桥接到NSDecimalNumber.但是,我遇到了使用NSDecimalNumber时无法重现的精度问题.
According to the docs here, Swift 3/4 Decimal type is a representation in base 10 bridged to NSDecimalNumber. However I'm having precision issues that do not reproduce when using NSDecimalNumber.
let dec24 = Decimal(integerLiteral: 24) let dec1 = Decimal(integerLiteral: 1) let decResult = dec1/dec24*dec24 // prints 0.99999999999999999999999999999999999984 let dn24 = NSDecimalNumber(value: 24) let dn1 = NSDecimalNumber(value: 1) let dnResult = dn1.dividing(by: dn24).multiplying(by: dn24) // prints 1小数"结构不准确,还是我误会了什么?
Shouldn't the Decimal struct be accurate, or am I misunderstanding something?
推荐答案NSDecimalNumber(及其覆盖类型Decimal)可以代表
...可以表示为mantissa x 10^exponent的任何数字,其中mantissa是长度不超过38位的十进制整数,而exponent是从–128到127的整数.
... any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer from –128 through 127.
因此,十进制分数(最多38个十进制数字)可以表示 准确,但不是任意数字.特别是1/24 = 0.416666666... 具有无限多个小数位数(重复小数),并且不能为 完全表示为Decimal.
So decimal fractions (with up to 38 decimal digits) can be represented exactly, but not arbitrary numbers. In particular 1/24 = 0.416666666... has infinitely many decimal digits (a repeating decimal) and cannot be represented exactly as a Decimal.
Decimal和NSDecimalNumber之间也没有精度差异.如果我们打印出差异,这将变得显而易见 在实际结果和理论结果"之间:
Also there is no precision difference between Decimal and NSDecimalNumber. That becomes apparent if we print the difference between the actual result and the "theoretical result":
let dec24 = Decimal(integerLiteral: 24) let dec1 = Decimal(integerLiteral: 1) let decResult = dec1/dec24*dec24 print(decResult - dec1) // -0.00000000000000000000000000000000000016 let dn24 = NSDecimalNumber(value: 24) let dn1 = NSDecimalNumber(value: 1) let dnResult = dn1.dividing(by: dn24).multiplying(by: dn24) print(dnResult.subtracting(dn1)) // -0.00000000000000000000000000000000000016更多推荐
Swift的小数精度问题
发布评论