我想用 C++ 求解方程组。有没有提供求解器的工具/包?我的系统看起来像
(x-a)^2 + (y-b)^2 = d1
(x-c)^2 + (y-d)^2 = d2
在这种情况下我知道 a,...,d, d1,d2。
据我所知,我采用了一个特殊情况(a,b,d = 0,并且c不为0),但我想要所有情况下的解决方案。
有人有想法吗?
我建议你阅读《数字食谱》。 本书有一章是关于方程求解的,其前言通常以足够简单的术语对所有主题进行了很好的概述。 请注意,以数值方式求解方程有许多细节,并且使用任何包而不处理细节可能会导致不好的解决方案(或者可能只是速度慢,或者不够好)。
几何意义上的方程组(SOE) 代表两个圆。第一个是一个圆圈,其 中心位于 (a,b) 且半径为 sqrt(d1),并且 第二个是 (c,d) 处的圆,半径为 sqrt(d2)。
需要考虑三种情况
the first case is if the two circles do not
intersect. In this case the equation does not have a
solution.
The second case is if the two circles intersect at
two points. In such case the equations will have two
solutions. i.e two possible values for (x,y)
In third case the two circles intersect at exactly
two points. In this case the SOE has exactly one
solution. i.e one pair of solution (x,y).
那么我们如何检查国有企业是否有解决方案。好吧,我们 检查两个圆是否相交。 两个圆相交当且仅当: 两圆之间的距离小于或 等于它们的半径之和。
sqrt( (a-c)^2 + (b-d)^2 ) <= sqrt(d1) + sqrt(d2).
如果等式成立则两个圆相交 正好一个点,因此国有企业正好有一个 解决方案。
我可以继续解释,但我会给你留下 方程。看看这个:
是的,这个支持非线性系统和重载^运算符。
您可以使用这个非常简单的非线性方程求解器库: https://github.com/tomwillow/tomsolver
对于你的问题,我写了一些代码:
#include <tomsolver/tomsolver.hpp>
using namespace tomsolver;
int main() {
std::setlocale(LC_ALL, ".UTF8");
try{
// create equations as a symbolic vector
SymVec f{
Parse("(x-a)^2 + (y-b)^2") - Var("d1"),
Parse("(x-c)^2 + (y-d)^2") - Var("d2"),
};
// replace known values
f.Subs(VarsTable{
{"a", 1.0},
{"b", 2.0},
{"c", 3.0},
{"d", 4.0},
{"d1", 100.0},
{"d2", 100.0},});
cout << f << endl;
// solve
auto ans = Solve(f);
cout << "x = "<<ans["x"] << endl;
cout << "y = "<<ans["y"] << endl;
}catch (const std::exception &err){
std::cerr << err.what() << std::endl;
return -1;
}
return 0;
}
并得到结果:
[(x-1)^2+(y-2)^2-100
(x-3)^2+(y-4)^2-100]
x = 9
y = -4