How to get the Strength of some whole in Swift?

I’ve been studying fast lately, but I have a major problem that cannot find the answer

I want to get something like

var a:Int = 3 var b:Int = 3 println( pow(a,b) ) // 27 

but the pow function can only work with a double number, it does not work with an integer, and I can't even get int to double something like Double (a) or a.double () ...

Why does he not provide the power of the whole? it will definitely return an integer without ambiguity! and why can't I tell the integer to double? it just changes 3 to 3.0 (or 3.00000 ... whatever)

If I get two integers and I want to do a power operation, how can I do it smoothly?

Thank!

+86
double integer swift pow
Jun 13 '14 at 2:13
source share
17 answers

If you like, you can declare an infix operator to do this.

 // Put this at file level anywhere in your project infix operator ^^ { associativity left precedence 160 } func ^^ (radix: Int, power: Int) -> Int { return Int(pow(Double(radix), Double(power))) } // ... // Then you can do this... let i = 2 ^^ 3 // ... or println("2³ = \(2 ^^ 3)") // Prints 2³ = 8 

I used two carriages so you can still use the XOR operator.

Update for Swift 3

In Swift 3, the magic number of precedence is replaced by precedencegroups :

 precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence } infix operator ^^ : PowerPrecedence func ^^ (radix: Int, power: Int) -> Int { return Int(pow(Double(radix), Double(power))) } // ... // Then you can do this... let i2 = 2 ^^ 3 // ... or print("2³ = \(2 ^^ 3)") // Prints 2³ = 8 
+73
Jun 13 '14 at 8:37
source share

Besides the fact that your variable declarations have syntax errors, this works exactly as you expected. All you have to do is cast a and b to Double and pass the values ​​to pow . Then, if you are working with 2 Ints and want to return Int to the other side of the operation, just cast it back to Int.

 import Darwin let a: Int = 3 let b: Int = 3 let x: Int = Int(pow(Double(a),Double(b))) 
+44
Jun 13 '14 at 2:19
source share

Sometimes casting Int to Double not a viable solution. In some quantities, this conversion loses accuracy. For example, the following code does not return what you might intuitively expect.

 Double(Int.max - 1) < Double(Int.max) // false! 

If you want accuracy with large values and you don't need to worry about negative metrics - which in general cannot be solved with integers - then this implementation of the tail recursive squaring algorithm is your best bet. According to this SO answer , this is "the standard method for modular exponentiation for huge numbers in asymmetric cryptography."

 // using Swift 5.0 func pow<T: BinaryInteger>(_ base: T, _ power: T) -> T { func expBySq(_ y: T, _ x: T, _ n: T) -> T { precondition(n >= 0) if n == 0 { return y } else if n == 1 { return y * x } else if n.isMultiple(of: 2) { return expBySq(y, x * x, n / 2) } else { // n is odd return expBySq(y * x, x * x, (n - 1) / 2) } } return expBySq(1, base, power) } 

Note: in this example, I used the generic T: BinaryInteger . This is so that you can use Int or UInt or any other integer type.

+10
Aug 18 '16 at 14:57
source share

If you really want to implement only "Int only" and do not want to force to / from Double , you need to implement it. Here is a trivial implementation; there are faster algorithms, but this will work:

 func pow (base:Int, power:UInt) -> Int { var answer : Int = 1 for _ in 0..power { answer *= base } return answer } > pow (2, 4) $R3: Int = 16 > pow (2, 8) $R4: Int = 256 > pow (3,3) $R5: Int = 27 

In a real implementation, you probably want to check out some errors.

+5
Jun 13 '14 at 5:12
source share

a little more details more

  infix operator ^^ { associativity left precedence 160 } func ^^ (radix: Int, power: Int) -> Int { return Int(pow(CGFloat(radix), CGFloat(power))) } 

swift - Binary Expressions

+4
Apr 18 '15 at 22:36
source share

If you are not prone to operator overloading (although the ^^ solution is probably clear to someone reading your code), you can do a quick implementation:

 let pwrInt:(Int,Int)->Int = { a,b in return Int(pow(Double(a),Double(b))) } pwrInt(3,4) // 81 
+4
Jul 08 '15 at 20:53 on
source share

mklbtz correctly refers to exponential by squaring the standard algorithm for calculating integer powers, but the tail-recursive implementation of the algorithm seems a bit confusing. See http://www.programminglogic.com/fast-exponentiation-algorithms/ for a non-recursive implementation of squaring in C. In I tried to translate it to Swift here:

 func expo(_ base: Int, _ power: Int) -> Int { var result = 1 while (power != 0){ if (power%2 == 1){ result *= base } power /= 2 base *= base } return result } 

Of course, this may be due to the creation of an overloaded operator to call it, and it can be rewritten to make it more universal, so that it works on everything that implements the IntegerType protocol. To make it general, I would probably start with something like

  func expo<T:IntegerType>(_ base: T, _ power: T) -> T { var result : T = 1 

But this is probably addicted.

+4
Dec 01 '16 at 11:20
source share

Combining answers into an overloaded set of functions (and using "**" instead of "^^", as some other languages ​​use, is clearer for me):

 // http://stackoverflow.com/questions/24196689/how-to-get-the-power-of-some-integer-in-swift-language // Put this at file level anywhere in your project infix operator ** { associativity left precedence 160 } func ** (radix: Double, power: Double) -> Double { return pow(radix, power) } func ** (radix: Int, power: Int ) -> Double { return pow(Double(radix), Double(power)) } func ** (radix: Float, power: Float ) -> Double { return pow(Double(radix), Double(power)) } 

When using Float, you may lose accuracy. If you use numeric literals and a combination of integers and non-integers, you will get Double by default. I personally like the ability to use a mathematical expression instead of a function like pow (a, b) for stylistic / readability, but that's just me.

Any statements that cause a pow () error will also call these functions to cause an error, so the burden of error checking is still in the code using the power function. KISS, IMHO.

Using the native pow () function allows, for example, to take square roots (2 ** 0.5) or inverse (2 ** -3 = 1/8). Due to the ability to use inverse or fractional measures, I wrote all my code to return the double type of pow () function by default, which should return maximum accuracy (if I remember the documentation correctly). If necessary, this can be reset using an Int or Float type or something else, possibly with a loss of precision.

 2 ** -3 = 0.125 2 ** 0.5 = 1.4142135623731 2 ** 3 = 8 
+3
Oct 17 '15 at 3:34
source share

Turns out you can also use pow() . For example, you can use the following to express 10 to 9.

 pow(10, 9) 

Along with pow , powf() returns a number with float instead of double . I tested this only on Swift 4 and macOS 10.13.

+3
Feb 14 '18 at 23:38
source share

Or simply:

 var a:Int = 3 var b:Int = 3 println(pow(Double(a),Double(b))) 
+1
May 31 '15 at 18:46
source share

To calculate power(2, n) , simply use:

 let result = 2 << (n-1) 
+1
06 Oct '17 at 1:36 on
source share

Swift 4.x Version

 precedencegroup ExponentiationPrecedence { associativity: right higherThan: MultiplicationPrecedence } infix operator ^^: ExponentiationPrecedence public func ^^ (radix: Float, power: Float) -> Float { return pow((radix), (power)) } public func ^^ (radix: Double, power: Double) -> Double { return pow((radix), (power)) } public func ^^ (radix: Int, power: Int) -> Int { return NSDecimalNumber(decimal: pow(Decimal(radix), power)).intValue } 
+1
Mar 16 '18 at 9:32
source share

In Swift 5:

 extension Int{ func expo(_ power: Int) -> Int { var result = 1 var powerNum = power var tempExpo = self while (powerNum != 0){ if (powerNum%2 == 1){ result *= tempExpo } powerNum /= 2 tempExpo *= tempExpo } return result } } 

Use like this

 2.expo(5) // pow(2, 5) 

Thanks to Paul Buis's answer.

+1
Jun 30 '19 at 15:32
source share

Trying to combine overload, I tried using generics, but could not get it to work. I finally decided to use NSNumber instead of trying to overload or use generics. This simplifies the following:

 typealias Dbl = Double // Shorter form infix operator ** {associativity left precedence 160} func ** (lhs: NSNumber, rhs: NSNumber) -> Dbl {return pow(Dbl(lhs), Dbl(rhs))} 

The following code is the same function as above, but implements error checking to check if the parameters can be converted to pair numbers successfully.

 func ** (lhs: NSNumber, rhs: NSNumber) -> Dbl { // Added (probably unnecessary) check that the numbers converted to Doubles if (Dbl(lhs) ?? Dbl.NaN) != Dbl.NaN && (Dbl(rhs) ?? Dbl.NaN) != Dbl.NaN { return pow(Dbl(lhs), Dbl(rhs)) } else { return Double.NaN } } 
0
Oct 22 '15 at 4:59
source share

add

 extension Int { func pow(_ lhr: Int, _ rhr: Int) -> Int { return Int(Foundation.pow(Double(lhr), Double(rhr))) } } 

and you can use your code

 var a:Int = 3 var b:Int = 3 println( pow(a,b) ) // 27 
0
Jul 03 '19 at 14:44
source share

I like it better

 func ^ (left:NSNumber, right: NSNumber) -> NSNumber { return pow(left.doubleValue,right.doubleValue) } var a:NSNumber = 3 var b:NSNumber = 3 println( a^b ) // 27 
-one
Aug 02 '14 at 9:52
source share
  func calc (base:Int, number:Int) -> Int { var answer : Int = base for _ in 2...number {answer *= base } return answer } calc (2,2) 
-3
Jul 24 '14 at
source share



All Articles