hi, 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.
+4
A:
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.
Mark Byers
2010-03-31 01:11:40
Thank you very much.
kshama
2010-03-31 01:20:20
+2
A:
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
Mladen Jablanović
2010-03-31 09:45:39
A:
You can use something different like:
number**(-1)
that is the same as
1.0/number
fl00r
2010-03-31 10:16:41