Reputation: 696
I am doing some calculation using Swift. I understand that in Swift, 0/0 gives NAN (not a number) instead of 0. Is there anyway for it to return 0 instead?
for x in 0..<n {
for y in 0..<n {
if(B[0,y,x]==NAN) {B[0,y,x]=0 } //use of undeclared identifier 'NAN'
println("\((Float)B[0,y,x])")
}
}
Upvotes: 5
Views: 10628
Reputation: 2459
NaN is defined in FloatingPointType
protocol.
Which is the Swift equivalent of isnan()?
Then, if you want zero, how about using Overflow Operators?
let x = 1
let y = x &/ 0
// y is equal to 0
[UPDATED]
You can define custom overflow operator like this.
func &/(lhs: Float, rhs: Float) -> Float {
if rhs == 0 {
return 0
}
return lhs/rhs
}
var a: Float = 1.0
var b: Float = 0
// this is 0
a &/ b
Upvotes: 13
Reputation: 441
good answer from @bluedome, in case you want this as an extension and\or have any errors there is an answer
infix operator &/ {}
extension CGFloat {
public static func &/(lhs: CGFloat, rhs: CGFloat) -> CGFloat {
if rhs == 0 {
return 0
}
return lhs/rhs
}
}
then you can divide by zero
let a = 5
let b = 0
print(a &/ b) // outputs 0
Upvotes: 6