Integer division with rounding - ruby

I need to do integer division. I expect the following to return 2 instead of the actual 1:
187 / 100 # => 1
This:
(187.to_f / 100).round # => 2
will work, but does't seem elegant as a solution. Isn't there an integer-only operator that does 187 / 100 = 2?
EDIT
I'll be clearer on my use case since I keep getting down-voted:
I need to calculate taxes on a price. All my prices are in cents. There is nothing below 1 cent in the accountability world so I need to make sure all my prices are integers (those people checking taxes don't like mistakes... really!)
But on the other hand, the tax rate is 19%.
So I wanted to find the best way to write:
def tax_price(price)
price * TAX_RATE / 100
end
that surely returns an integer, without any floating side effect.
I was afraid of going to the floating world because it has very weird side-effects on number representation like:
Ruby strange issue with floating point multiplication
ruby floating point errors
So I found it safer to stay in the integer or the fractional world, hence my question.

You can do it while remaining in the integer world as follows:
def round_div(x,y)
(x + y / 2) / y
end
If you prefer, you could monkey-patch Fixnum with a variant of this:
class Fixnum
def round_div(divisor)
(self + divisor / 2) / divisor
end
end
187.round_div(100) # => 2

No – (a.to_f / b.to_f).round is the canonical way to do it. The behavior of integer / integer is (for example) defined in the C standard as "discarding the remainder" (see http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf page 82) and ruby uses the native C function.

This is a less know method, Numeric#fdiv
You use it like this : 187.fdiv(100).round

Not sure, but this might be what you have in mind.
q, r = 187.divmod(100)
q + (100 > r * 2 ? 0 : 1) # => 2

This should work for you :
Use syntax like this.
(number.to_f/another_number).round
Example:
(18.to_f/5).round

As #MattW already answer (+1), you'd have to cast your integers to floats.
The only other way that is less distracting can be to add .0 to your integer:
(187.0 / 100).round
However, usually we don't operate on concrete integers but variables and this method would be no use.

After some thoughts, I could:
have used BigDecimals but it feels like a bazooka to kill a bird
or I can use a custom method that wouldn't use floating division within the process, as #sawa suggests
def rounded_integer_div(numerator, denominator)
q, r = numerator.divmod(denominator)
q + (100 > r * 2 ? 0 : 1)
end

If what you want is to actually only increase the result by 1 if there's any remainder (e.g. for counting paging/batching), you can use the '%' (modula operation) for remainders checking.
# to add 1 if it's not an even division
a = 187
b = 100
result = a / b #=> 1
result += 1 if (a % b).positive?
#=> 2
# or in one line
result = (a / b) + ((a % b).zero? ? 0 : 1)

Related

Why does .to_s break this code?

I'm working on a Codewars Ruby problem, and don't understand the error I'm seeing. Here are the instructions:
Coding decimal numbers with factorials is a way of writing out numbers
in a base system that depends on factorials, rather than powers of
numbers. In this system, the last digit is always 0 and is in base 0!.
The digit before that is either 0 or 1 and is in base 1!. The digit
before that is either 0, 1, or 2 and is in base 2!. More generally,
the nth-to-last digit in always 0, 1, 2, ..., or n and is in base n!.
Example : decimal number 463 is coded as "341010"
because 463 (base 10) = 3×5! + 4×4! + 1×3! + 0×2! + 1×1! + 0×0!
If we are limited to digits 0...9 the biggest number we can code is
10! - 1.
So we extend 0..9 with letters A to Z. With these 36 digits we can
code up to 36! − 1 = 37199332678990121746799944815083519999999910
(base 10)
We code two functions, the first one will code a decimal number and
return a string with the factorial representation :
"dec2FactString(nb)"
the second one will decode a string with a factorial representation
and produce the decimal representation : "factString2Dec(str)".
Given numbers will be positive.
Note
You can hope tests with Big Integers in Clojure, Python, Ruby, Haskel
but not with Java and others where the number "nb" in
"dec2FactString(nb)" is at most a long.
Ref: http://en.wikipedia.org/wiki/Factorial_number_system
def dec2FactString(nb)
if nb <= 0 then
num = 1
else
num = (nb * dec2FactString(nb - 1))
end
return num
end
Note that this method is only the first half of the problem. This code appears to work inasmuch as it returns the correct factorial, as a Fixnum when using this test:
Test.assert_equals(dec2FactString(4), "24")
Since the instructions ask for a string, I'd normally think that just adding ".to_s" to the num variable would take care of that, but instead I'm seeing a consistent "String can't be coerced into Fixnum (TypeError)" error message. I've tried pushing the output to an array and printing from there, but saw the same error.
I read up on Fixnum a little, and I understand the error in terms of adding a Fixnum to a string won't work, but I don't think I'm doing that in this case - I just want to convert the Fixnum output into a string. Am I missing something?
Observe - this code breaks and produces the error below it:
def dec2FactString(nb)
if nb <= 0 then
num = 1
else
num = (nb * dec2FactString(nb - 1))
end
return num.to_s
end
Example from description
`*': String can't be coerced into Fixnum (TypeError)
from `dec2FactString'
from `dec2FactString'
from `dec2FactString'
from `dec2FactString'
from `block in
'
from `block in describe'
from `measure'
from `describe'
from `
'
You're calling this function recursively. If you calculated the factorial of 1 and left to_s in there, it'd be fine since you're not reusing the variable.
However, if you do place to_s in there, what would you expect the result of num = (nb * dec2FactString(nb - 1)) to be? dec2FactString would be returning a str instead of a Fixnum, and you can't/shouldn't be able to do multiplication between a number and a string.
What you could do is split the responsibilities of stringification and calculation by creating two methods - one that delegates to the recursive function, and one that coerces its result into a string.
def dec2FactString(nb)
return fact(nb).to_s
end
def fact(nb)
if nb <= 0 then
1
else
nb * fact(nb - 1)
end
end
Firstly, Factorial is only defined on non-negative numbers and so your first test is incorrect (if nb <= 0). The recursion should stop when the number is 0 and should return 1 at that point.
Because your recursion returns a string and not a number, you cannot multiply the string by a Fixnum in the next round of recursion. Your recursion can be expanded via the substitution method to the following.
dec2FactString(5)
5 * dec2FactString(4)
5 * 4 * dec2FactString(3)
5 * 4 * 3 * dec2FactString(2)
5 * 4 * 3 * 2 * dec2FactString(1)
5 * 4 * 3 * 2 * 1 * dec2FactString(0)
5 * 4 * 3 * 2 * 1 * "1"
... That is the point where the recursion ends in an error since dec2FactString(0) returns "1"
It would be far better to break it into two functions. One that calculates factorial recursively and one that converts the final answer to a string. Also, you don't need to explicitly return a value in Ruby. The last line of a function is the return value.
I won't give you the complete code as you won't learn anything. As a few hints, do some research on tail call optimisation, recursion and return values in Ruby. This will allow you to craft a better implementation of the recursive function.
Happy coding!

Comparing two Integers by their divisibility

For instance:
8 > 10 = true, since 8 is divisible by 2 three times and 10 only once.
How can I compare two integers from any range of numbers? Are the modulo and divide operator capable of doing this task?
Use binary caculate to judge it
def devided_by_two(i)
return i.to_s(2).match(/0*$/).to_s.count('0')
end
To make integer divisibility by 2, just transcode it to binary and judge how many zero from end of banary number. The code I provide can be more simple I think.
Yes, they are capable. A number is even if, when you divide it by two, the remainder is zero.
Hence, you can use a loop to continuously divide by two until you get an odd number, keeping a count of how many times you did it.
The (pseudo-code) function for assigning a "divisibility by two, continuously" value to a number would be something like:
def howManyDivByTwo(x):
count = 0
while x % 2 == 0:
count = count + 1
x = x / 2 # make sure integer division
return count
That shouldn't be too hard to turn into Ruby (or any procedural-type language, really), such as:
def howManyDivByTwo(x)
count = 0
while x % 2 == 0
count = count + 1
x = x / 2
end
return count
end
print howManyDivByTwo(4), "\n"
print howManyDivByTwo(10), "\n"
print howManyDivByTwo(11), "\n"
print howManyDivByTwo(65536), "\n"
This outputs the correct:
2
1
0
16
Astute readers will have noticed there's an edge case in that function, you probably don't want to try passing zero to it. If it was production code, you'd need to catch that and act intelligently since you can divide zero by two until the cows come home, without ever reaching an odd number.
What value you return for zero depends on needs you haven't specified in detail. Theoretically (mathematically), you should return infinity but I'll leave that up to you.
Notice that you will likely mess up much of your code if you redefine such basic method. Knowing that, this is how it's done:
class Integer
def <=> other
me = self
return 0 if me.zero? and other.zero?
return -1 if other.zero?
return 1 if me.zero?
while me.even? and other.even?
me /= 2
other /= 2
end
return 0 if me.odd? and other.odd?
return -1 if me.odd?
return 1 if other.odd? # This condition is redundant, but is here for symmetry.
end
end

ruby math issue with division

I'm calculating Fibonacci numbers with binet's formula and I'm having trouble dividing in ruby. I've tried casting numbers to_f etc with no avail. I'll show you what works and what doesn't then maybe you can tell me why.
The following doesn't work
n=5
fib=(1 + sqrt(5))**n - (1-sqrt(5))**n / (2**n * sqrt(5))
puts fib #outputs 354.9257634247335 which is a bunch of garbage
I've also tried
n=5
fib=((1 + sqrt(5))**n).to_f - ((1-sqrt(5))**n).to_f / (2**n * sqrt(5)).to_f
puts fib #outputs the exact same thing as above
BUT The following works
n=5
fib1=(1 + sqrt(5))**n - (1-sqrt(5))**n
fib2=(2**n * sqrt(5))
fib = fib1/fib2
puts fib.round(0) #outputs 5 which is correct
Why do the first 2 examples fail but the latter gives me what I want? This is infuriating!
You have a problem with order of operations. Division has higher precedence than subtraction, so in the first two examples, only the second number is being divided.
You need to add a parenthesis around the numerator to make sure both parts are subtraced before being divided.
You are missing parenthesis
fib=((1 + sqrt(5))**n - (1-sqrt(5))**n) / (2**n * sqrt(5))
=> 5.000000000000001

A better Ruby implementation of round decimal to nearest 0.5

This seems horrible inefficient. Can someone give me a better Ruby way.
def round_value
x = (self.value*10).round/10.0 # rounds to two decimal places
r = x.modulo(x.floor) # finds remainder
f = x.floor
self.value = case
when r.between?(0, 0.25)
f
when r.between?(0.26, 0.75)
f+0.5
when r.between?(0.76, 0.99)
f+1.0
end
end
class Float
def round_point5
(self * 2).round / 2.0
end
end
A classic problem: this means you're doing integer rounding with a different radix. You can replace '2' with any other number.
Multiply the number by two.
round to whole number.
Divide by two.
(x * 2.0).round / 2.0
In a generalized form, you multiply by the number of notches you want per whole number (say round to .2 is five notches per whole value). Then round; then divide by the same value.
(x * notches).round / notches
You can accomplish this with a modulo operator too.
(x + (0.05 - (x % 0.05))).round(2)
If x = 1234.56, this will return 1234.6
I stumbled upon this answer because I am writing a Ruby-based calculator and it used Ruby's Money library to do all the financial calculations. Ruby Money objects do not have the same rounding functions that an Integer or Float does, but they can return the remainder (e.g. modulo, %).
Hence, using Ruby Money you can round a Money object to the nearest $25 with the following:
x + (Money.new(2500) - (x % Money.new(2500)))
Here, if x = $1234.45 (<#Money fractional:123445 currency:USD>), then it will return $1250.00 (#
NOTE: There's no need to round with Ruby Money objects since that library takes care of it for you!

Large Exponents in Ruby?

I'm just doing some University related Diffie-Hellman exercises and tried to use ruby for it.
Sadly, ruby doesn't seem to be able to deal with large exponents:
warning: in a**b, b may be too big
NaN
[...]
Is there any way around it? (e.g. a special math class or something along that line?)
p.s. here is the code in question:
generator = 7789
prime = 1017473
alice_secret = 415492
bob_secret = 725193
puts from_alice_to_bob = (generator**alice_secret) % prime
puts from_bob_to_alice = (generator**bob_secret) % prime
puts bobs_key_calculation = (from_alice_to_bob**bob_secret) % prime
puts alices_key_calculation = (from_bob_to_alice**alice_secret) % prime
You need to do what is called, modular exponentiation.
If you can use the OpenSSL bindings then you can do rapid modular exponentiation in Ruby
puts some_large_int.to_bn.mod_exp(exp,mod)
There's a nice way to compute a^b mod n without getting these huge numbers.
You're going to walk through the exponentiation yourself, taking the modulus at each stage.
There's a trick where you can break it down into a series of powers of two.
Here's a link with an example using it to do RSA, from a course I took a while ago:
Specifically, on the second page, you can see an example:
http://www.math.uwaterloo.ca/~cd2rober/Math135/RSAExample.pdf
More explanation with some sample pseudocode from wikipedia: http://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method
I don't know ruby, but even a bignum-friendly math library is going to struggle to evaluate such an expression the naive way (7789 to the power 415492 has approximately 1.6 million digits).
The way to work out a^b mod p without blowing up is to do the mod ping at every exponentiation - I would guess that the language isn't working this out on its own and therefore must be helped.
I've made some attempts of my own. Exponentiation by squaring works well so far, but same problem with bigNum. such a recursive thing as
def exponentiation(base, exp, y = 1)
if(exp == 0)
return y
end
case exp%2
when 0 then
exp = exp/2
base = (base*base)%##mod
exponentiation(base, exp, y)
when 1 then
y = (base*y)%##mod
exp = exp - 1
exponentiation(base, exp, y)
end
end
however, it would be, as I'm realizing, a terrible idea to rely on ruby's prime class for anything substantial. Ruby uses the Sieve of Eratosthenes for it's prime generator, but even worse, it uses Trial division for gcd's and such....
oh, and ##mod was a class variable, so if you plan on using this yourselves, you might want to add it as a param or something.
I've gotten it to work quite quickly for
puts a.exponentiation(100000000000000, 1222555345678)
numbers in that range.
(using ##mod = 80233)
OK, got the squaring method to work for
a = Mod.new(80233788)
puts a.exponentiation(298989898980988987789898789098767978698745859720452521, 12225553456987474747474744778)
output: 59357797
I think that should be sufficient for any problem you might have in your Crypto course
If you really want to go to BIG modular exponentiation, here is an implementation from the wiki page.
#base expantion number to selected base
def baseExpantion(number, base)
q = number
k = ""
while q > 0 do
a = q % base
q = q / base
k = a.to_s() + k
end
return k
end
#iterative for modular exponentiation
def modular(n, b, m)
x = 1
power = baseExpantion(b, 2) #base two
i = power.size - 1
if power.split("")[i] == "1"
x = x * n
x = x % m
end
while i > 0 do
n *= n
n = n % m
if power.split("")[i-1] == "1"
x *= n
x = x % m
end
i -= 1
end
return x
end
Results, where tested with wolfram alpha
This is inspired by right-to-left binary method example on Wikipedia:
def powmod(base, exponent, modulus)
return modulus==1 ? 0 : begin
result = 1
base = base % modulus
while exponent > 0
result = result*base%modulus if exponent%2 == 1
exponent = exponent >> 1
base = base*base%modulus
end
result
end
end

Resources