开发者

how to find inverse of a number in ruby

Am new to ruby. Can any one tell me how to f开发者_JS百科ind 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


You can use something different like:

number**(-1)

that is the same as

1.0/number


If your number is Rational then you can use the component parts to create the inverse Rational value:

@rational = Rational(1,27)
@inverse = Rational(@rational.denominator, @rational.numerator)

Oddly Rational doesn't have an inverse function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜