Swift的小数精度问题

编程入门 行业动态 更新时间:2024-10-22 09:44:57
本文介绍了Swift的小数精度问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

根据文档此处,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的小数精度问题

本文发布于:2023-11-23 01:30:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619624.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:小数   精度   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!