var solveFun = function( f /*function*/, c /*closest to 0*/, from /*from what number*/, to /*to what number*/, ic /*increasement*/){ var arr = new Array(); for(var i =from ; i <= to ; i+=ic){ var r = f(i); if(Math.abs(r) <= c) {arr.push({x:i,y:r});} } if(arr.length == 0) {return undefined;} return arr; } var ret = solveFun(function (n){return n*n*n -3*n + 1},0.001,-10,20,0.001); if(ret == undefined){console.log("no answer.");} else { console.log(ret.length + "answer found "); for(var i = 0 ;i < ret.length; i++) console.log("x = " + ret[i].x + ", y= " + ret[i].y); }
原文:http://blog.csdn.net/lan_liang/article/details/36014263