[英]Return a preferred root from the square root of a function
我正在尝试解决以下特殊情况的方程,其中l = b = 0; 并且它应该返回完美平方函数的平方根,例如sqrt((xd)^ 2)。 这可以有两个解,(xd)或(dx)。 我想获得(xd)作为最终解决方案,但是该程序默认返回(dx)解决方案。 我尝试更改d和x的位置,但似乎无济于事。 这是我的程序:
float y(float x) {
float l=0., b=0., d=8.5, r_0=3., z_0=0.1;
return exp(-pow(x*x*cos(b*PI/180.)*cos(b*PI/180.)+d*d-2*d*x*cos(b*PI/180.)*cos(l*PI/180.), 0.5)/r_0)*exp(-x*pow(1-cos(b*PI/180.)*cos(b*PI/180.),0.5)/z_0) ;
}
int main(){
FILE* fp =NULL;
float x0,xn,step,s,int_val, tau; /* s = distance to the star from the sun*/
int i,n, j ;
scanf("%f%f%d",&x0,&xn,&n);
step = (xn-x0)/n;
s = y(x0) + y(xn);
fp = fopen("trap.txt", "w");
for(i = 1; i < n; i++) {
s += 2*y(x0+i*step);
fprintf(fp,"%e\n",s*step/2);
}
fclose(fp);
我假设您正在谈论这一部分:
-pow( x*x*cos( b*PI / 180. )*cos( b*PI / 180. ) + d*d - 2 * d*x*cos( b*PI / 180. )*cos( l*PI / 180. ), 0.5 )
首先,实际上有一个函数double sqrt( double x )
用于计算平方根。
第二件事是,与数学sqrt( square( anything ) )
结合, sqrt( square( anything ) )
将返回absolutevalue( anything )
。 在您的示例情况下, sqrt( (xd)^2 )
等同于absolutevalue( xd )
。 由于absolutevalue( xd )
等于absolutevalue( dx )
,因此更改值的位置不会改变任何内容。
如果x > d
,则将得出x - d
; 否则d - x
就是数学所说的。
无需更改位置,但您只需在整个sqrt( square( ) )
之前放置减号即可更改位置。 您已经有一个减号,只需删除即可。
知道平方根的平方根为绝对值,您也可以用fabs( x * cos( b * PI / 180. ) - d )
替换我上面写的特定提取物,其中fabs
是需要的函数double
绝对值,并且在math.h
定义。
使用替代词来代替重复性术语。 使用选择常量,简化。
#include <math.h>
#define PI 3.1415926535897932384626433832795
float y(float x) {
float l=0., b=0., d=8.5, r_0=3., z_0=0.1;
double y;
// y = exp(-pow(x*x*cos(b*PI/180.)*cos(b*PI/180.)+d*d-2*d*x*cos(b*PI/180.)*cos(l*PI/180.), 0.5)/r_0)
// y *= exp(-x*pow(1-cos(b*PI/180.)*cos(b*PI/180.),0.5)/z_0);
if (l != 0.0 || b != 0.0) {
double xcosb = x*cos(b*PI/180.);
double xsinb = x*sin(b*PI/180.);
double cosl = cos(l*PI/180.);
// general solution
y = exp(-sqrt(xcosb*xcosb - 2*xcosb*d*cosl + d*d)/r_0);
y *= exp(-xsinb/z_0); // @abiessu
} else {
// y = exp(-sqrt(x*x - 2*x*d*1.0 + d*d)/r_0);
// y *= exp(-0/z_0);
// y = exp(-sqrt((x-d)*(x-d))/r_0);
// y *= 1.0;
y = exp(-fabs(x - d))/r_0;
}
return y;
}
的确获得(xd)
作为最终解决方案。 建议OP查看功能是否正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.