Round negative integer coefficient to negative infinity

It seems that whole divisions in Swift are rounded to zero, and not to a smaller number. This means, for example, that -1 / 2 will be 0 instead of -1.

Is there a way to tell Swift to round to a lower number? I know how I can "imitate" it, but if I have my own solution, I would prefer to use it.

+7
rounding swift
source share
3 answers

You can define your own operator as follows:

 infix operator </> { associativity left } func </> (a: Int, b: Int) -> Int { return Int(floor(Double(a) / Double(b))) } 

so you don’t have to enter this absurd expression. I suggest </> , but of course you can choose your own.

If you don't like creating statements, use it as a regular function:

 func div (a: Int, b: Int) -> Int { return Int(floor(Double(a) / Double(b))) } 

Finally, but personally I would not use, you can override the division operator :

 func / (a: Int, b: Int) -> Int { return Int(floor(Double(a) / Double(b))) } 

and in this case it will be applied to all units - should be aware of side effects, although

+1
source share

The function is half rounded, so if you are executing floor(Float(a)/Float(b)) , it should work.

0
source share

The backup solution that I have associated with the new operator -/ . Mathematics does not involve shuffling back and forth between doubles and integers, which avoids some extreme cases with very large numbers. On the other hand, it can overflow if both the denominator and numerator are very large negative numbers, and I'm not sure what will happen if the denominator negative.

 infix operator -/ { precedence 150 associativity left } func -/ (numerator: Int, denominator: Int) -> Int { if numerator < 0 { return (numerator - (denominator - 1)) / denominator } return numerator / denominator } 

Any solution written in Swift terms is likely to end up with its share of problems resolved if you want to emulate C-behavior. Another possibility would be to include the tiny divide function in the bridge header and implement an operator with it.

0
source share

All Articles