我有两个数字,我需要找到这两个数字之间的算术级数,以使它始终包含数字zero。
下面是我的代码。
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
,则会得到缺少zero的[-7, -4.17, -1.33, 1.5, 4.33, 7.17, 10]
。
以下情况
numberOfPoints
是固定的min
,并且max
有所不同。min
始终为负max
可以为负,也可以不为负。A negative threshold value
可以加到min
上以获得数字为[[zero的算术级数。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步中获得arithmetic progression
,因为在6步中步的最小差为1001/6=166.86
,而如果包括0
,则步的最大值必须为1
以不超过最大值。添加负阈值并不重要,因为它只会增加step的值。
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 a positive 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
*/