简体   繁体   English

将函数e ^( - x)和e ^( - x ^ 2)传递给C中的计算函数

[英]Pass functions e^(-x) and e^(-x^2) into a function for computation in C

I have to write a program that passes the functions e^(-x) and e^(-x^2) into another function, called calculateIntegral() , which will then calculate the integral of the function. 我必须编写一个程序,将函数e^(-x)e^(-x^2)传递给另一个函数,称为calculateIntegral() ,然后计算函数的积分。

Restrictions: 限制:

  • calculateIntegral() is the function which will be used to compute the integral of both e^(-x) and e^(-x^2) calculateIntegral()是用于计算e^(-x)e^(-x^2)的积分的函数
  • I can only have the function passed, the a and b bounds, and the number of intervals as the arguments for function calculateIntegral() . 我只能传递函数, ab边界以及间隔数作为函数calculateIntegral()的参数。

I've thought about changing x to, say, -x outside the function and assigning it to another variable to compute in e^(x) , but then I would have to include that as another argument in calculateIntegral() . 我已经考虑过在函数外部将x更改为-x ,并将其分配给另一个变量来计算e^(x) ,但是我必须将它作为另一个参数包含在calculateIntegral()

Is there any way to alter the original e^(x) , so that when it gets passed into calculateIntegral() , it would be e^(-x) so the rest function would just have to plug the bounds into that equation for calculations? 有没有办法改变原始的e^(x) ,所以当它被传递到calculateIntegral() ,它将是e^(-x)所以其余函数只需将边界插入该等式进行计算?

What you want is to parametrize the integrand, so you want to be able to pass the function that f has to integrate as a parameter. 你想要的是参数化被积函数,所以你希望能够传递f必须作为参数集成的函数。 In C, this can be done with function pointers : 在C中,这可以通过函数指针完成:

// IntegrandT now is the type of a pointer to a function taking a double and
// returning a double
typedef double (*IntegrandT)(double);

// The integration function takes the bound and the integrand function
double f(double min, double max, IntegrandT integrand)
{
    // here integrand will be called as if it were a "normal" function
}

// Your example functions
double minusExp(double x)
{
    return exp(-x);
}

double unitaryGaussian(double x)
{
    return exp(-x*x);
}

// now you can do
double res=f(-10, 10, minusExp);
double res2=f(-10, 10, unitaryGaussian);

For more details about function pointers, check your C manual. 有关函数指针的更多详细信息,请查看C手册。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM