本帖最后由 flyer_2001 于 2024-3-2 11:59 编辑
[HTML] 纯文本查看 复制代码 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Nonlinear Equation Solver</title>
<script>
// 定义已知参数
/*
A*X+B*Y=C (M*X-A*X*X)/O=(N*Y-B*Y*Y)/P
A B C M N O P 值已知 求X和Y的值
*/
var A = 289/* ... */;
var B = 20/* ... */;
var C = 3522.6/* ... */;
var M = 88278.28/* ... */;
var N =34616.49 /* ... */;
var O = 1200/* ... */;
var P = 500/* ... */;
// 定义方程组函数
function f1(X, Y) {
return A * X + B * Y - C;
}
function f2(X, Y) {
return (M * X - A * X * X) / O - (N * Y - B * Y * Y) / P;
}
// 定义雅可比矩阵函数
function jacobian(X, Y) {
return [
[A, B],
[(M - 2 * A * X) / O, -(N - 2 * B * Y) / P]
];
}
// 定义牛顿法迭代函数
function newtonMethod(X0, Y0, tolerance, maxIter) {
var X = X0, Y = Y0;
for (var iter = 0; iter < maxIter; iter++) {
var J = jacobian(X, Y);
var det = J[0][0] * J[1][1] - J[0][1] * J[1][0];
if (Math.abs(det) < 1e-6) { // 检查雅可比矩阵是否奇异
console.error("Jacobian matrix is singular. No solution found.");
return null;
}
var J_inv = [[J[1][1], -J[0][1]], [-J[1][0], J[0][0]]]; // 计算雅可比矩阵的逆
var invDet = 1 / (det);
J_inv[0][0] *= invDet;
J_inv[0][1] *= invDet;
J_inv[1][0] *= invDet;
J_inv[1][1] *= invDet;
var f = [f1(X, Y), f2(X, Y)];
var delta = [J_inv[0][0] * f[0] + J_inv[0][1] * f[1],
J_inv[1][0] * f[0] + J_inv[1][1] * f[1]];
X -= delta[0];
Y -= delta[1];
if (Math.sqrt(delta[0] * delta[0] + delta[1] * delta[1]) < tolerance) {
return {X: X, Y: Y};
}
}
console.error("Maximum iterations reached. No solution found.");
return null;
}
// 页面加载完成后执行计算
window.onload = function() {
var initialGuessX = 1/* ... */; // 初始猜测值X
var initialGuessY =1 /* ... */; // 初始猜测值Y
var tolerance = 1e-6; // 容差
var maxIter = 100; // 最大迭代次数
var result = newtonMethod(initialGuessX, initialGuessY, tolerance, maxIter);
if (result) {
document.getElementById('output').textContent = `X = ${result.X}, Y = ${result.Y}`;
} else {
document.getElementById('output').textContent = 'No solution found.';
}
};
</script>
</head>
<body>
<h1>Nonlinear Equation Solver</h1>
<p>Results:</p>
<p id="output"></p> <!-- 这里将显示X和Y的值 -->
</body>
</html> |