作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
嗨,我正在编写一些程序来查找不同正弦函数的解决方案。我想要 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/
我是一名优秀的程序员,十分优秀!