import numeric from 'numeric';
function polyfit(x, y, degree) {
const len = x.length;
const A = numeric.rep([degree + 1, degree + 1], 0);
const B = numeric.rep([degree + 1, 1], 0);
for (let i = 0; i < degree + 1; i++) {
for (let j = 0; j < degree + 1; j++) {
for (let k = 0; k < len; k++) {
A[i][j] += Math.pow(x[k], i + j);
}
}
for (let k = 0; k < len; k++) {
B[i][0] += Math.pow(x[k], i) * y[k];
}
}
let coeffs
coeffs = numeric.solve(A, B);
return coeffs;
}
function evaluatePolynomial(coeffs, x) {
let result = 0;
for (let i = 0; i < coeffs.length; i++) {
result += coeffs[i] * Math.pow(x, i);
}
return result;
}
function findMaxOfPolynomial(coeffs, xRange) {
// 这里使用简单的搜索方法来找到多项式在指定范围内的最大值
// 实际应用中可能需要更复杂的数值方法,比如梯度下降或牛顿法等
let maxValue = -Infinity;
let maxX = 0;
const step = (xRange[1] - xRange[0]) / 1000; // 假设步长为范围的千分之一
for (let x = xRange[0]; x <= xRange[1]; x += step) {
const y = evaluatePolynomial(coeffs, x);
if (y > maxValue) {
maxValue = y;
maxX = x;
}
}
return {
maxValue,
maxX
};
}
function comixFunction(coeffs) {
let result = '';
for (let i = 0; i < coeffs.length; i++) {
// result.push(coeffs[i] +'*x^'+ i);
if (coeffs[i] < 0 || i === 0) {
result = result + coeffs[i] + '*x^' + i
} else {
result = result + '+' + coeffs[i] + '*x^' + i
}
}
return 'y=' + result;
}
function getMaxData(dataX, dataY) {
let coeffx = []
let chaList = []
// 循环遍历从二次函数到十次函数
for (let i = 2; i <= 10; i++) {
let cellGroup = polyfit(dataX, dataY, i)
let cha = 0
for (let j = 0; j < dataX.length; j++) {
cha = cha + (dataY[j] - evaluatePolynomial(cellGroup, dataX[j]))
}
chaList.push(cha)
coeffx.push(cellGroup);
}
let minIndex = chaList.findIndex((value, index, arr) => {
return arr[index] === Math.min(...chaList)
});
console.log("最合理的最高项次数为:" + (minIndex + 1))
// 得出比值最小的那个函数
console.log("最合理的多项式系数列表为:", coeffx[minIndex])
console.log("最合理的多项式系数:", comixFunction(coeffx[minIndex]))
// 查找多项式在指定范围内的最大值
const xRange = [Math.min(...dataX), Math.max(...dataX)]; // 稍微扩展范围以查找可能的最大值
const {
maxValue,
maxX
} = findMaxOfPolynomial(coeffx[minIndex], xRange);
console.log('多项式在指定范围内的最大值:', maxValue);
console.log('对应的x值:', maxX);
}
export default getMaxData
引入这个文件,直接使用getMaxData,基本逻辑就是从二次多项式拟合到十次多项式,然后用dataX,得出的值和原始数据dataY进行差值求和,差距最小的最为最合适的,这个js只能用于较为简单的数据拟合,如果复杂难度较高的,不建议使用
使用这个方法需要下包numeric
npm install numeric
将文件复制粘贴到项目内,引入该文件
import getMaxData from '自己放的js路径'
使用
let xdata = [1,2,3,4,5]
let ydata = [2,4,6,7,8]
getMaxData(xdata, ydata)