Problems with massive decimal

I have strange behavior on this function. At some point (when share is 39.0 / 100) cake became more than one on a console, but the assert does not invoke. I attach the log from the console. May be I am absolutely stupid in an implementing of that algorithm, but where am I?


struct IntrestingTask {
    func calculate() {
        var cake = 1.0
        var pupils = 100
        var array = [(pipulNumber: Int, amount: Double)]()
        var index = 1
        var currentpercent = 1.0
        while pupils > 0 {
            let piece = cake * Double((currentpercent/100))
            cake -= piece
            print("piece: \(piece), share: \(currentpercent) / 100, decimal: \(Double(currentpercent/100)) cake: \(cake)")
            assert(cake < 1)
            array.append((index, piece))
            index += 1
            currentpercent = Double(index)
            pupils -= 1
        let sorted = array.sorted { $0.amount < $1.amount }
 //       array.forEach { print($0) }

I try to describe the task. It is a school task about pupils and cake. There are 100 pupils and one cake.
First takes 1 percent from the cake. Second takes 2 percent from the reminder and so one. Which pupil takes a biggest piece?

But when I execute same expression in REPL it returns fine.

The results here are all less than one; they're written in what's called scientific notation. The e-05 on the end of the number means the number is multiplied by pow(10, -5), or can be thought of as shifting the decimal point five places to the right. Your code is doing the right thing.

As a side note, you're not actually dealing with decimals here, but rather floating point arithmetic, since many decimals can't be exactly represented by a computer without taking up a lot of space. For what you're doing, floating point arithmetic should be completely fine, but it's a good thing to be aware of – just remember those numbers you're getting in the console may not be exact.


To add on a bit, one should also be aware that the printed representation may not reflect the precise value of the floating point value. That's on top of the value itself not precisely representing the result of the operation which created it.

String representations often truncate and round, and not all transforms will round the same way, so how you print can change the apparent result.

Terms of Service

Privacy Policy

Cookie Policy