我一直试图为自己编写一个交叉点计算器。由于某种原因,我的计算器编码完全错误或预期的操作顺序不起作用。请允许我详细说明。
def point_of_intersection (m1, b1, m2, b2)
if m1 == m2 || m1 - m2 == 0
puts "No Solution"
elsif m1 == m2 || b1 == b2
puts "Infinite Solutions"
end
x = -1 * (b1 - b2) / (m1 - m2)
y = (m1 * x) + b1
puts "The Point Of Intersection is: (#{x}, #{y})"
end
如您所见,方法point_of_intersection有四个参数: 第一个线性方程(m1)的斜率及其y轴截距(b1) 和第二线性方程(m2)的斜率及其y轴截距(b2)
对于某些情况,此计算器对我来说正常工作,但对于其他一些情况,它似乎输出错误的数字。以下是我的一些测试结果
point_of_intersection(1, 4, 2, 6) #Gives (-2,2) which is correct
point_of_intersection(0,5,2,0) #Gives (2,5) when it should be (2.5, 5)
point_of_intersection(1,2,5,3) #Gives (-1, 1) when it should be (-0.25, 1.75)
我知道有些人可能会很快质疑y-intercept差异的-1倍除以斜率值之差的公式是否合适。我可以保证,对于我在文本编辑器上执行的每个测试,我也在纸上使用了完全相同的公式,并得到了不同的结果。
我最好的猜测是我的电脑以某种方式执行
的操作顺序x = -1 * (b1 - b2) / (m1 - m2)
然而,我没有足够的经验来确定计算机如何搞砸了操作。
感谢您的所有帮助,谢谢。
答案 0 :(得分:0)
将您的参数转换为浮点数:
def point_of_intersection (m1, b1, m2, b2)
m1 = m1.to_f
b1 = b1.to_f
m2 = m2.to_f
b2 = b2.to_f
if m1 == m2 || m1 - m2 == 0
puts "No Solution"
elsif m1 == m2 || b1 == b2
puts "Infinite Solutions"
end
x = -1 * (b1 - b2) / (m1 - m2)
y = (m1 * x) + b1
puts "The Point Of Intersection is: (#{x}, #{y})"
end
示例:
point_of_intersection(1, 4, 2, 6)
#The Point Of Intersection is: (-2.0, 2.0)
point_of_intersection(0, 5, 2, 0)
#The Point Of Intersection is: (2.5, 5.0)
point_of_intersection(1, 2, 5, 3)
#The Point Of Intersection is: (-0.25, 1.75)
答案 1 :(得分:0)
你需要使用浮动:
x = (-1 * (b1 - b2) / (m1 - m2)).to_f
y = ((m1 * x) + b1).to_f