Am new to ruby. Can any one tell me how to find inverse of a number in ruby.Is there any function for it? or just 1/number ? Thanks in advance.
You need to use floating point numbers:
1.0 / number
If you use 1 / number, and number is the integer 5, you'll just get 0 instead of 0.2.
Although not exactly an answer to your question, I think we should mention here Rational class, suitable for keeping rational numbers without the loss implied with storage of float-point numbers, i.e. in form of fractions:
n = 3
#=> 3
r = Rational(1,3)
#=> 13 # don't let this confuse you, this is 1/3 in fact
r.to_s
#=> "1/3"
You can perform usual rational arithmetic on such numbers, keeping the fractions' accuracy:
r = r * r
#=> 19
r.to_s
#=> "1/9"
And, eventually, you can convert these numbers to ordinary floats:
r.to_f
#=> 0.111111111111111
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With