gpt4 book ai didi

c - 如何将多项式代入正弦函数? (关于)

转载 作者:行者123 更新时间:2023-11-30 20:04:02 28 4
gpt4 key购买 nike

嗨,我正在编写一些程序来查找不同正弦函数的解决方案。我想要 sin(2x)、sin(4x)、sin(6x)、...sin(12x) 并将它们存储到数组中,以便我可以在给定的时间间隔内测试每个函数的解决方案。

这是代码...

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>

int bisect(double *x, double x0, double xf, double tolerance, double (*func)(double));


int main()
{
double x, x0 = 2.0, xf = 4.0, tolerance = FLT_EPSILON;
int status, i, j;
double (*pf[6])(double);

for (i = 1; i < 7; i++)
{
pf[i] = sin(2 * i * x);
// error : cannot assign double value to double(*) (double) entity
// How to make functions like sin(2x), sin(4x), .. etc??
status = bisect(&x, x0, xf, tolerance, pf[i]);

我创建了 bisect() 函数来查找给定函数返回 0 的时间点。

二分函数位于主函数下方。 x0是起点,xf是终点,我设置了检查误差的容差。 bisect 函数在 for 循环中使用中间值定理。

我想通过在 for 循环中调用 bisect 函数并使用 *pf[i] 传递正弦函数来找到解决方案。

        if (status == -1)
printf("Error : bisect() failed, invalid tolerance\n");
else if(status == -2)
printf("Error : bisect() failed, invalid end points\n");
else
printf("x = %f, sin(x) = %g\n", x, pf[i](x));


}
return 0;
}

int bisect(double *x, double x0, double xf, double tolerance, double (*func)(double))
{
double xleft = x0, fleft;
double xright = xf;
double xmid, fmid;

if (tolerance <= 0.0)
return -1;

fleft = func(x0);

if (fleft * func(xf) > 0.0)
return -2;

xmid = (xleft+xright) /2.0;
fmid = func(xmid);

while (fabs(fmid) > tolerance)
{
if (fleft * fmid <= 0)
{
xright = xmid;
}

else
{
xleft = xmid;
fleft = fmid;
}
xmid = (xleft + xright) / 2.0;
fmid = func(xmid);

}
*x = xmid;
return 0;
}

很容易找到 sin、cos 等的解,但是 sin(2x)、sin(4x) 等呢?我如何将这些函数存储在 *pf[] 中? (函数指针数组)

任何建议都会有帮助。

最佳答案

在 C 中,如果不创建多个包装原始 sin 函数的函数,就不可能做你想做的事。

也许是这样的

double sin2(double value)
{
return sin(2 * value);
}

double sin4(double value)
{
return sin(4 * value);
}

// Etc...

int main(void)
{
double (*pf[6])(double) = {
sin2, sin4, ...
};

for (int i = 0; i < 6; ++i)
{
printf("%f\n", pf[i](0.5));
}
}

关于c - 如何将多项式代入正弦函数? (关于),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44241878/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com