求下列方程组的解:
x 2 + y 2 − 8 = 0 x^2 + y^2 - 8= 0 x2+y2−8=0
x − y = 0 x - y = 0 x−y=0
运行结果:
可见与真实解
(
x
=
2
,
y
=
2
)
(x = 2, y = 2)
(x=2,y=2) 或
(
x
=
−
2
,
y
=
−
2
)
(x = -2, y = -2)
(x=−2,y=−2)之一已经十分接近。实际上,通过修改代码可以把另一个解也求出来,此略。
思路:
构造目标函数 L = ( x 2 + y 2 − 8 ) 2 + ( x − y ) 2 L=(x^2 + y^2 - 8)^2 + (x - y)^2 L=(x2+y2−8)2+(x−y)2, 显然当 L = 0 L = 0 L=0时的解,就是原方程组的解 。因此随机确定 x x x和 y y y,当 L L L与 0 0 0十分接近时,此时的 x x x和 y y y就是方程组的近似解。
代码如下:
#include <iostream>
#include "Random.h"
#include <cmath>
#define MAX_V 100
using namespace std;
float L(float x, float y){
float f1 = x * x + y * y - 8;
float f2 = x - y;
return f1 * f1 + f2 * f2;
}
int main(){
Random rand;
float x = 0;
float y = 0;
float l = L(x,y);
while(l >= 0.01){
float dir = rand.rand() * 2 * 3.14159;
float len = rand.rand(); // 产生 [0, 1)的随机数
float dx = len * cos(dir);
float dy = len * sin(dir);
float dl = L(x + dx, y + dy) - l;
if(dl < 0){ //如果随机产生的x,y可以令目标函数变小
x += dx;
y += dy;
l += dl;
}
}
cout << "solve : x = " << x << " y = " << y << endl;
return 0;
}