Math Divison in Swift

Math divison in Swift

Your code is performing integer division, taking the integer result and converting it to a double. Instead, you want to convert these individual integers to doubles and then do the division. So, instead of

let result = (Double(myInt! / lutning) * Double(pi))

You should

let result = Double(myInt!) / Double(lutning) * Double(pi)

Note, Double already has a .pi constant, so you can remove your pi constant, and simplify the above to:

let result = Double(myInt!) / Double(lutning) * .pi

Personally, I’d define myInt and lutning to be Double from the get go (and, while we’re at it, remove all of the forced unwrapping (with the !) of the optionals):

guard
let text = graderna.text,
let text2 = radien.text,
let value = Double(text),
let value2 = Double(text2)
else {
return
}

let lutning: Double = 360
let result = value / lutning * .pi

Or, you can use flatMap to safely unwrap those optional strings:

guard
let value = graderna.text.flatMap({ Double($0) }),
let value2 = radien.text.flatMap({ Double($0) })
else {
return
}

let lutning: Double = 360
let result = value / lutning * .pi

(By the way, if you’re converting between radians and degrees, it should be 2π/360, not π/360.)

Divide two numbers and return fraction in swift

To get the quotient and remainder of a division, you can use the quotientAndRemainder(dividingBy:) function.

3.quotientAndRemainder(dividingBy: 6) // (quotient 0, remainder 3)

If you want to get the floating point result of a division, use the / operator on two floating point numbers.

Either do

let result = 3.0 / 6.0 // 0.5

or if your integers are coming from variables, do

let result = Double(3.0) / Double(6.0) // 0.5

Why can't I divide integers in swift?

The OP seems to know how the code has to look like but he is explicitly asking why it is not working the other way.

So, "explicitly" is part of the answer he is looking for: Apple writes inside the "Language Guide" in chapter "The Basics" -> "Integer and Floating-Point Conversion":

Conversions between integer and floating-point numeric types must be
made explicit

How to execute multiplications and/or divisions in the right order?

If you only have the four operations +, -, x, and ÷, you can do this by keeping track of a pendingOperand and pendingOperation whenever you encounter a + or -.

Then compute the pending operation when you encounter another + or -, or at the end of the calculation. Note that + or - computes the pending operation, but then immediately starts a new one.

I have modified your function to take the stringNumbers, operators, and initial values as input so that it could be tested independently in a Playground.

func calculateTotal(stringNumbers: [String], operators: [String], initial: Double) -> Double {

func performPendingOperation(operand: Double, operation: String, total: Double) -> Double {
switch operation {
case "+":
return operand + total
case "-":
return operand - total
default:
return total
}
}

var total = initial
var pendingOperand = 0.0
var pendingOperation = ""

for (i, stringNumber) in stringNumbers.enumerated() {
if let number = Double(stringNumber) {
switch operators[i] {
case "+":
total = performPendingOperation(operand: pendingOperand, operation: pendingOperation, total: total)
pendingOperand = total
pendingOperation = "+"
total = number
case "-":
total = performPendingOperation(operand: pendingOperand, operation: pendingOperation, total: total)
pendingOperand = total
pendingOperation = "-"
total = number
case "÷":
total /= number
case "×":
total *= number
default:
break
}
}
}

// Perform final pending operation if needed
total = performPendingOperation(operand: pendingOperand, operation: pendingOperation, total: total)

// clear()
return total
}

Tests:

// 4 + 3    
calculateTotal(stringNumbers: ["3"], operators: ["+"], initial: 4)
7
// 4 × 3
calculateTotal(stringNumbers: ["3"], operators: ["×"], initial: 4)
12
// 2 + 2 × 4
calculateTotal(stringNumbers: ["2", "4"], operators: ["+", "×"], initial: 2)
10
// 2 × 2 + 4
calculateTotal(stringNumbers: ["2", "4"], operators: ["×", "+"], initial: 2)
8
// 17 - 2 × 3 + 10 + 7 ÷ 7
calculateTotal(stringNumbers: ["2", "3", "10", "7", "7"], operators: ["-", "×", "+", "+", "÷"], initial: 17)
22

Division operator not working as expected (swift)

You're dividing two integers, so integer division is used. To avoid this, you could explicitly cast the operands to Doubles:

self.pairChance = Double(self.pairCount) / Double(self.rollCount) * 100.0

Why can't I divide integers correctly within reduce in Swift?

The division does not yield a double; you're doing integer division.

You're not getting ((1 + 2) + 3 etc.) / 5.

In the first case, you're getting (((((0 + (1/5 = 0)) + (2/5 = 0)) + (3/5 = 0)) + (4/5 = 0)) + (5/5 = 1)) = 0 + 0 + 0 + 0 + 0 + 1 = 1.

In the second case, you're getting ((((((0 + 1) + 2) + 3) + 4) + 5) / 5) = 15 / 5 = 3.

In the third case, double precision loss is much smaller than the integer, and you get something like (((((0 + (1/5.0 = 0.2)) + (2/5.0 = 0.4)) + (3/5.0 = 0.6)) + (4/5.0 = 0.8)) + (5/5.0 = 1.0)).

Objective C vs Swift math operations

Does anybody know why the difference?

You've just made a simple grouping error.

As you figured out both Objective-C and Swift require a cast when converting from a floating-point value to an integer one, so you have written (int)a for the former and Int(a) for the latter.

You have also understood that converting from an integer to a floating-point value differs in the two languages, in Objective-C (and C and lots of other languages) the conversion is implicit whereas in Swift it is explicit.

The only mistake you have made is in parsing the Objective-C and hence producing the wrong Swift or you've simply mis-typed the Swift.

In arithmetic expressions operators are evaluated according to a priority, relevant to your problem casts bind tightly to the following expression, multiplication and division is done next, then addition and subtraction. What this means is your Objective-C:

a - (int) a / 360 * 360

is parsed as:

a - (double) ( (int) a / 360 * 360 )

note that the (double) cast applies to the result of the expression (int) a / 360 * 360. What you've written in Swift is:

a - Double(Int(a)) / 360 * 360

which isn't the same, here the cast only applies to Int(a). What you should have written is:

a - Double(Int(a) / 360 * 360)

which applies the cast to Int(a) / 360 * 360 just as the Objective-C does.

With that correction in both languages the multiplication and division all operate on integers, and integer division is truncating (e.g. 9 / 4 is 2 not 2.25). With the misplaced parenthesis in Swift the multiplication and division all operate on floating-point values.

TL;DR: You just misplaced a parenthesis.

HTH

Why is x / 100 == 0 when x != 0 in swift?

Since i and 100 are both integer values, / will do integer division and the result will be truncated to 0.

Even when you do let xValue: Float = Float(i/100), the result of division inside the parentheses is already truncated to 0 before the value can be converted to a Float.

Convert i to a floating-point value before dividing to prevent the result from being truncated.

for i in 1...100{
let xValue = Float(i)/100
print(xValue)
}


Related Topics



Leave a reply



Submit