建议尝试以下几行,这实际上是一种寻找epsilon
价值的二分搜索(使用术语https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm)在 和 的目标点长度范围simpTargetLo
内simpTargetHi
。
(请注意,我没有对此进行测试,因为我无权访问coordSimplify()
,因此可能存在一些语法错误,但逻辑应该是合理的。)
// Set the acceptable result.
let simpTargetLo = 490;
let simpTargetHi = 510;
// Set the initial epsilon range which needs to be outside the estimated solution.
let epsilonLo = 0;
let epsilonHi = 1;
let epsilonMid;
// Calculate the initial low and high simp values.
let simpLo = coordSimplify(data.tableData, epsilonLo);
let simpHi = coordSimplify(data.tableData, epsilonHi);
let simpMid;
// Ensure that the initial simp values fall outside the target range.
if ( !( simpLo.length <= simpTargetLo && simpTargetHi <= simpHi.length ) ) {
throw new Error( `Initial epsilon need expanding.\n epsilonLo ${epsilonLo} returns ${simpLo.length}\n epsilonHi ${epsilonHi} returns ${simpHi.length}` );
}
// Finally, let's ensure we don't get into an infinite loop in the event that
// their is no solution or the solution oscillates outside the target range.
let iterations = 0;
let maxIterations = 100;
do {
// Calculate the simp at the midpoint of the low and high epsilon.
epsilonMid = ( epsilonLo + epsilonHi ) / 2;
simpMid = coordSimplify(data.tableData, epsilonMid );
// Narrow the epsilon low and high range if the simp result is still outside
// both the target low and high.
if ( simpMid.length < simpTargetLo ) {
epsilonLo = epsilonMid;
} else if ( simpTargetHi < simpMid.length ) {
epsilonHi = epsilonMid;
} else {
// Otherwise, we have a solution!
break;
}
iterations++;
while( iterations < maxIterations );
if ( iterations < maxIterations ) {
console.log( `epsilon ${epsilonMid} returns ${simpMid.length}` );
} else {
console.log( `Unable to find solution.` );
}
请注意,这种缩小到解决方案的方法取决于正确选择初始epsilonLo
和epsilonHi
,此外还假设它coordSimplify()
本质上是相当连续的......