模拟退火法求椭圆离原点最短距离

有一个椭圆方程 ax^2+by^2+cz^2+dyz+exz+fxy ,其中输入为,a,b,c,d,e,求结果精确到小数点后8位

百度了一下,学习到了模拟退火法,写这篇博客进行记录

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
const double eps = 1e-8; //精度
const double r = 0.99;   //降温速度
const int dx[] = { 0, 0, 1, -1, 1, -1, 1, -1 }; //向8个方向降温
const int dy[] = { 1, -1, 0, 0, -1, 1, 1, -1 };
double a, b, c, d, e, f;
 
double dis(double x, double y, double z)        //求距离
{   
    return sqrt(x * x + y * y + z * z);
}
 

double getz(double x, double y)           //已知x,y,求z,二元一次方程
{ 
    double A = c, B = e * x + d * y,C = a * x * x + b * y * y + f * x * y - 1;
    double delta = B * B - 4 * A * C;
    if (delta < 0) return 1e60;
    double z1 = (-B + sqrt(delta)) / 2 / A,z2 = (-B - sqrt(delta)) / 2 / A;
    if (z1 * z1 < z2 * z2) 
    return z1;
    else 
    return z2;
}
 
double solve()          //模拟退火
{
    double step = 1;    //步长
    double x = 0, y = 0, z;
    while (step > eps) 
    {
        z = getz(x, y);
        for (int i = 0; i < 8; ++i) 
        {
            double nx = x + dx[i] * step,
                   ny = y + dy[i] * step,
                   nz = getz(nx, ny);
            if (nz > 1e30) continue;
            if (dis(nx, ny, nz) < dis(x, y, z)) 
            {
                x = nx; y = ny; z = nz;
            }
        }
        step *= r;
    }
    return dis(x, y, z);
}
 
int main() 
{
    while (scanf("%lf%lf%lf%lf%lf%lf", &a, &b, &c, &d, &e, &f) != EOF) 
    {
        printf("%.8f\n", solve());
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值