本文簡要介紹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類。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。