Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find inverse of a number in ruby

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.

like image 535
kshama Avatar asked Feb 03 '26 18:02

kshama


2 Answers

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.

like image 74
Mark Byers Avatar answered Feb 06 '26 07:02

Mark Byers


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
like image 37
Mladen Jablanović Avatar answered Feb 06 '26 08:02

Mladen Jablanović