gpt4 book ai didi

ruby - 选择最小斜差的两个坐标

转载 作者:数据小太阳 更新时间:2023-10-29 08:59:52 25 4
gpt4 key购买 nike

我正在尝试制作一个可以整理的函数最小斜差的两个坐标。

具体来说,输入数据是:

  1. standard_dot(一个数组) 例如[0,0]
  2. other_dots(一个数组由 7 个数组组成) [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8]]

“calculate_min_dif”函数会做接下来的事情:

  1. 计算 standard_dot 和数组 other_dots 中的 7 个点之间的斜率。
  2. 选择斜率最接近的一组 2 个点
  3. 返回数组中这 2 个点的索引。
   def calculate_min_dif(standard_dot, other_dots)
index = 0
slope_list = Array.new(7)

other_dots.each do |dot|
slope_list[index] = (( standard_dot[1]-dot[1] ) / (standard_dot[0]-dot[0] )).abs
index = index + 1
end

result = slope_list.index(slope_list.combination(2).min_by { |a,b| (a-b).abs })
return result
end

编译器说问题在第 6 行

nil can't be coerced into Fixnum
(repl):6:in `-'
(repl):6:in `block in calculate_min_dif'
(repl):6:in `combination'
(repl):6:in `each'
(repl):6:in `min_by'
(repl):6:in `calculate_min_dif'

表示-右边,b的值为nil我不知道为什么...

对不起,如果我太愚蠢了。我是 Ruby 和英语的新手(有点……)谢谢

最佳答案

您可以按如下方式进行。我会留给其他人来解释您收到错误消息的原因。

base_pt = [0,0]
pts = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8]]

def slope((x,y), (bpt_x, bpt_y))
((y - bpt_y).to_f/(x - bpt_x)).round(5)
end

def slope_diff(pt1, pt2, base_pt)
(slope(pt1, base_pt)-slope(pt2, base_pt)).abs
end

pts.combination(2).min_by { |pt1, pt2| slope_diff(pt1, pt2, base_pt) }
#=> [[6, 7], [7, 8]]

让我们对照斜坡检查一下。

pts.each_with_object({}) { |pt, h| h[pt] = slope(pt, base_pt).round(5) }
#=> {[1, 2]=>2.0, [2, 3]=>1.5, [3, 4]=>1.33333, [4, 5]=>1.25,
# [5, 6]=>1.2, [6, 7]=>1.16667, [7, 8]=>1.14286}

您可以看到通过 base_pt 和点 [6, 7][7, 8] 的线具有斜率的最小绝对差。

关于ruby - 选择最小斜差的两个坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38650729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com