本文简要介绍ruby语言中 Rational类
的用法。
有理数可以表示为一对整数:a/b (b>0),其中 a 是分子,b 是分母。 Integer
a 在数学上等于有理数 a/1。
您可以使用以下命令显式创建 Rational 对象:
您可以使用以下方法将某些对象转换为 Rationals:
-
方法Rational。
例子
Rational(1) #=> (1/1)
Rational(2, 3) #=> (2/3)
Rational(4, -6) #=> (-2/3) # Reduced.
3.to_r #=> (3/1)
2/3r #=> (2/3)
您还可以从浮点数或字符串创建有理对象。
Rational(0.3) #=> (5404319552844595/18014398509481984)
Rational('0.3') #=> (3/10)
Rational('2/3') #=> (2/3)
0.3.to_r #=> (5404319552844595/18014398509481984)
'0.3'.to_r #=> (3/10)
'2/3'.to_r #=> (2/3)
0.3.rationalize #=> (3/10)
有理对象是一个精确的数字,它可以帮助您编写没有任何舍入错误的程序。
10.times.inject(0) {|t| t + 0.1 } #=> 0.9999999999999999
10.times.inject(0) {|t| t + Rational('0.1') } #=> (1/1)
但是,当表达式包含不精确的组件(数值或运算)时,它将产生不精确的结果。
Rational(10) / 3 #=> (10/3)
Rational(10) / 3.0 #=> 3.3333333333333335
Rational(-8) ** Rational(1, 3)
#=> (1.0000000000000002+1.7320508075688772i)
相关用法
- Ruby Rational.inspect用法及代码示例
- Ruby Rational.rational <=>用法及代码示例
- Ruby Rational to_i()用法及代码示例
- Ruby Rational.rat ** numeric用法及代码示例
- Ruby Rational quo()用法及代码示例
- Ruby Rational positive?()用法及代码示例
- Ruby Rational ceil()用法及代码示例
- Ruby Rational inspect()用法及代码示例
- Ruby Rational.round用法及代码示例
- Ruby Rational.denominator用法及代码示例
- Ruby Rational.rationalize用法及代码示例
- Ruby Rational.rat * numeric用法及代码示例
- Ruby Rational.ceil用法及代码示例
- Ruby Rational abs()用法及代码示例
- Ruby Rational.rat / numeric用法及代码示例
- Ruby Rational to_s()用法及代码示例
- Ruby Rational.floor用法及代码示例
- Ruby Rational.fdiv用法及代码示例
- Ruby Rational negative?()用法及代码示例
- Ruby Rational.truncate用法及代码示例
- Ruby Rational fdiv()用法及代码示例
- Ruby Rational truncate()用法及代码示例
- Ruby Rational floor()用法及代码示例
- Ruby Rational denominator()用法及代码示例
- Ruby Rational.magnitude用法及代码示例
注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Rational类。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。