简体   繁体   English

有没有办法在swift 4中迭代double var的小数部分?

[英]Is there any way to iterate the decimal part of a double var in swift 4?

What i'm looking for: 我在找什么:

Given a Double (doublenumber) and an Int (n) I wish to iterate trough the 1st decimal, 2nd decimal, 3rd decimal, 4th decimal.... until the 'n'decimal 给定一个Double(双数字)和一个Int(n)我想迭代第一个小数,第二个小数,第三个小数,第四个十进制......直到'n'decimal

My first approach was, coverting to String the Double so I could iterate like an array the string, but the problem is that when I convert to string I lose many decimals numbers 我的第一种方法是,转换为String the Double所以我可以像数组一样迭代字符串,但问题是,当我转换为字符串时,我会丢失许多小数

    let doubleNumber = 1.00/98                  //0.010204081632653061224489795918367346938775510204081632653...
    var stringFromDouble = String(doubleNumber) //0.010204081632653
    stringFromDouble.removeFirst()              //.010204081632653
    stringFromDouble.removeFirst()              //010204081632653

    for letter in stringFromDouble{
      //cycle to iterate the decimals
    }

If the intention is to get many decimal digits of 1.0/98.0 then you must not store that number in a Double in the first place, because that has a precision of approximately 16 decimal digits only. 如果打算获得1.0/98.0 许多十进制数字,那么您不能首先将该数字存储在Double中,因为它的精度仅为大约16位十进制数字。 You could use Decimal which has a precision of 38 decimal digits. 你可以使用Decimal其中有38位十进制数字的精度。

But for more decimal digits you'll have to do “rational arithmetic,” ie work with numerator and denominator of the fraction as integers. 但是对于更多的十进制数字,你必须做“有理算术”,即用分数的分子和分母作为整数。

Here is how you can print arbitrarily many decimal digits of a rational number. 以下是如何打印有理数的任意多个十进制数字。 For simplicity I have assumed that the number is positive and less than one. 为简单起见,我假设数字为正数且小于1。

func printDecimalDigits(of numerator: Int, dividedBy denominator: Int, count: Int) {
    var numerator = numerator
    for _ in 1...count {
        // Multiply by 10 to get the next digit:
        numerator *= 10
        // Print integer part of `numerator/denominator`:
        print(numerator / denominator, terminator: "")
        // Reduce `numerator/denominator` to its fractional part:
        numerator %= denominator
    }
    print()
}

Example: 例:

printDecimalDigits(of: 1, dividedBy: 98, count: 100)
// 0102040816326530612244897959183673469387755102040816326530612244897959183673469387755102040816326530

Or as a function which returns the digits as a (lazily evaluated) sequence: 或者作为将数字作为(延迟评估的) 序列返回的函数

func decimalDigits(of numerator: Int, dividedBy denominator: Int) -> AnySequence<Int> {
    return AnySequence(sequence(state: numerator) { num -> Int in
        num *= 10
        let d = num / denominator
        num %= denominator
        return d
    })
}

Example: 例:

let first1000Digits = decimalDigits(of: 1, dividedBy: 98).prefix(1000)
for d in first1000Digits { print(d) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM