[英]Find arithmetic progression between two numbers
我有两个数字,我需要在这两个数字之间找到一个等差数列,它应该始终包含数字零。
下面是我的代码。
var numberOfPoints = 6;
var min = -5;
var max = 10;
var step = (max - min) / numberOfPoints;
var pointsArray = [min];
var point = min;
for (var i = 0; i < numberOfPoints; i++) {
point = point + step;
pointsArray.push(+point.toFixed(2));
}
console.log(pointsArray); //[-5, -2.5, 0, 2.5, 5, 7.5, 10]
代码工作正常。
但是,如果我更改min = -7
, [-7, -4.17, -1.33, 1.5, 4.33, 7.17, 10]
得到缺少零的[-7, -4.17, -1.33, 1.5, 4.33, 7.17, 10]
。
以下是情况
numberOfPoints
是固定的min
和max
变化。min
始终为负max
可能是也可能不是负值。A negative threshold value
添加到min
以获得其中包含数字零的等差数列。此任务无法解决
Following is the situation
- numberOfPoints is fixed min and max varies.
- min is always negative max may or may not be negative.
- A negative threshold value can be added to min to get an arithmetic progression having number zero in it.
证明: numberOfPoints= 6
, min=-1000
和max=1
,你不能在 6 步中得到 0 的arithmetic progression
,因为在 6 步中,步长的最小差异是1001/6=166.86
,而如果你包括0
,则最大值of step 必须为1
才能不超过最大值。
添加负阈值无关紧要,因为它只会增加步长的值。
PS:我在上面的例子中忽略了这一步min is always negative max may or may not be negative.
,因为这一步更容易证明不可解。 min=-10
, max=-9
,它们之间没有零并且添加负阈值不会改变它。
/* min and max must have opposite signs, because there's no zero between two negative numbers but they cannot be arbitrary, they have to satisfy a condition if the k-th term of the progression is zero then min + k * step = 0 or min + k * (max - min) / numberOfPoints = 0 from which k = - numberOfPoints * min / (max - min) the condition is that - numberOfPoints * min / (max - min) must be an integer in the interval [1, numberOfPoints] otherwise there's no solution in the first example that you have (-6) * (-5) / (10 - (-5)) = 3 but in the second (-6) * (-7) / (10 - (-7)) = 2.470588235294118 (-4, 2), (-3, 3), (-2, 4) will all work, but (-2, 3) won't */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.