退火写挂了,求助
  • 板块灌水区
  • 楼主xueruo
  • 当前回复15
  • 已保存回复15
  • 发布时间2023/4/15 17:09
  • 上次更新2023/10/23 18:24:41
查看原帖
退火写挂了,求助
638718
xueruo楼主2023/4/15 17:09
#include<cmath>
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<climits>
#define int long long
#define rd rand()<<15|rand()
#define randouble rand()/RAND_MAX 
#define MAX_TIME 0.95
using namespace std;
double a,b,c,ans;
double calc(double x) {
	double res = 0;
	return a*x*x+b*x+c;
}
void fire() {
	double T = 10000;
	double nowx = rd;
	double T_k=1e-5;
	while (T > T_k) {
		double nxt = nowx + T * (randouble * 2 - 1);
		double delta = calc(nxt) - calc(nowx);
		if(delta<0){//解更优 
			nowx = nxt;//接受新解 
		}else if (exp(-delta / T) > randouble){//不优 
			nowx = nxt;//接受新解 
		} 
		T *= 0.995;
	}
	if(calc(nowx)<calc(ans)){
		ans=nowx;
	}
}
signed main() {
	srand(time(0));
	cout<<"请输入二次函数 y=ax^2+bx+c的参数a,b,c\n";
	cin>>a>>b>>c;
	while ((double)clock()/CLOCKS_PER_SEC < MAX_TIME) fire();
	cout<<"f("<<ans<<")="<<calc(ans)<<"\n";
	return 0;
}

input:input:
11 11 11
output:output:
f(0)=1f(0)=1
realans:realans:
f(−0.5)=0.75f(-0.5)=0.75

2023/4/15 17:09
加载中...