用蛮力解方程

Using brute-force for solving equations

本文关键字:方程      更新时间:2023-10-16

我正试图用蛮力在c++中求解一个非常简单的方程。基本思想是向上或向下计算x的值,直到方程的左侧等于右侧。我没有得到任何错误,但x的值总是0.01或-0.01。我认为我的do/while循环是有缺陷的,但你们可能都比我更有经验,所以我们很感激任何帮助。

#include <iostream>
using namespace std;
int main()
{
double x, y, z, q, w;
x = 0;
cout << "enter y*x + q = z*x + w in order of appearance" << endl;
cin >> y;
cin >> q;
cin >> z;
cin >> w;
if ((y-z)/(w-q) > 0) // checks if x is positive
{
do
{
(x = x + 0.01);
} while ((y * x + q) == (z * x + w));
}
else if ((y - z) / (w - q) < 0) // checks if x is negative
{
do
{
(x = x - 0.01);
} while ((y * x + q) == (z * x + w));
}
else
{
x = 0;
}
cout << "x is " << x << endl;
return 0;
}

谢谢!

一些事情。

首先,当比较浮点数时,您可能希望在一个较小的范围内进行比较,通常称为epsilon。这一点尤其正确,因为你的增量相当大——0.01。你可能跳过了你想要的值。

我要做的是关注:

  • 我离答案越来越近还是越来越远
  • 我跳过答案了吗

一些代码:

float leftSide = y * x + q;
float rightSide = z * x + w;
float delta = leftSide - rightSide;
if (abs(delta) < epsilon) {
// You're really close
}

还要注意,如果y和z是相同的值,这将永远不会起作用,除非q和w也是。