我有一個 Ruby 類,它通過繼承內置模塊 Comparable 和 sqrt 方法來比較 x 和 y 兩個值的大小。但不幸的是,我不明白def scalar代碼中的計算內容是什么?
在下面的示例中,Ruby 的執行結果是 v1 大于 v2,但如果我單獨列印 v1 和 v2 的結果,我只會胡說八道。所以我的第二個問題是,v1 和 v2 的結果值是多少?
class Vector
include Comparable
attr_accessor :x, :y
def initialize(x, y)
@x, @y = x, y
end
def scalar
Math.sqrt(x ** 2 y ** 2)
end
def <=> (other)
scalar <=> other.scalar
end
end
v1 = Vector.new(2, 6)
v2 = Vector.new(4, -4)
puts v1 #=> #<Vector:0x000055a6d11794e0>
puts v2 #=> #<Vector:0x000055a6d1179490>
p v1 <=> v2 #=> 1
p v1 < v2 #=> false
p v1 > v2 #=> ture
uj5u.com熱心網友回復:
Math.sqrt(x ** 2 y ** 2)正在使用良好的舊畢達哥拉斯來計算向量端點到原點的笛卡爾距離,即向量的長度。對于v1這個是 6.324555320336759,對于v2結果是 5.656854249492381。
要檢查 Ruby 物件,請使用p而不是puts.
p v2 # <Vector:0x0000000109a1eb40 @x=4, @y=-4>
uj5u.com熱心網友回復:
v1 和 v2 的結果值是多少?
覆寫 to_s
class Vector
def to_s
"x = #{x} : y = #{y} : scalar = #{'%.6f' % scalar}"
end
end #Vector
你得到這個輸出:
puts v1 # => x = 2 : y = 6 : scalar = 6.324555
puts v2 # => x = 4 : y = -4 : scalar = 5.656854
uj5u.com熱心網友回復:
scalar命名會更好magnitude,因為它使用勾股定理計算向量的長度。如果您不熟悉向量和勾股定理,我建議您在繼續撰寫更多代碼之前先學習這里的數學概念。這些概念對于理解它們在代碼中的使用方式至關重要。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/426757.html
標籤:红宝石
下一篇:計算陣列Ruby中字串之間的距離
