Skip to content

Instantly share code, notes, and snippets.

@numist
Last active April 5, 2024 19:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save numist/76254a4642417084f43a to your computer and use it in GitHub Desktop.
Save numist/76254a4642417084f43a to your computer and use it in GitHub Desktop.
Python-style exponentiation with the ** operator.
infix operator **: MultiplicationPrecedence
public func **<T: UnsignedInteger>(base: T, exponent: T) -> T {
return pow(base, exponent)
}
/// Implements pow() for integers using exponentiation by squaring
public func pow<T: BinaryInteger, U: UnsignedInteger>(_ base: T, _ exponent: U) -> T {
var result: T = 1
// copy the parameters using .init(T) in case either happens to use a reference type
var base = T(base)
var exponent = U(exponent)
while true {
if exponent % 2 == 1 {
result *= base
}
exponent >>= 1
if exponent == 0 { break }
base *= base
}
return result
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import Darwin
public func **(base: Double, exponent: Double) -> Double {
return pow(base, exponent)
}
public func **(base: Float, exponent: Float) -> Float {
return powf(base, exponent)
}
#endif
@shepting
Copy link

Would this work for both cases?

func **<T>(lhs: T, rhs: T) -> T {
    return pow(lhs, rhs)
}

@numist
Copy link
Author

numist commented Apr 5, 2024

pow is a C function provided by Darwin that's only implemented for double

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment