如何正确使用exp和sqrt属性

时间:2019-02-08 22:36:31

标签: c signed normal-distribution negative-number exp

-使用双精度 -使用sqrt()和指数函数exp() -使用*计算平方 -不要使用pow()

我正在获得价值,这些价值与我的预期无关。我尝试使它们全部签名,但没有任何改变,并且尝试打印出12位小数,并且似乎没有任何效果。我已经链接了数学库并对其进行了定义。

double normal(double x, double sigma, double mu)
{   
     double func = 1.0/(sigma * sqrt(2.0*M_PI));
     double raise = 1.0/2.0*((x-mu)/sigma);
     double func1 = func * exp(raise);
     double comp_func = (func1 * func1);

     return comp_func;
}
int main(void)
{
// create two constant variables for μ and σ
const double sigma, mu;
//create a variable for x - only dynamic variable in equation
unsigned int  x;

//create a variable for N values of x to use for loop
int no_x;

//scaniing value into mu
printf("Enter mean u: ");   
scanf("%lf", &mu);

//scanning  value into sigma
printf("Enter standard deviation: ");   
scanf("%lf", &sigma);

//if sigma = 0  then exit
if(sigma == 0)
{
    printf("error you entered: 0");
    exit(0);
}

//storing number of x values in no_x
printf("Number of x values: "); 
scanf("%d", &no_x);

//the for loop where i am calling function normal N times
for(int i = 1; i <= no_x; i++)
{

    //printing i for the counter in prompted x values
    printf("x value %d : ", i);

    // scanning in x
    scanf("%lf", &x);


    x = normal(x,sigma,mu);

    printf("f(x) = : %lf.12", x);

    printf("\n");
}

return 0;   
}

C:>。\ a.exe 输入平均值u:3.489 输入std dev s:1.203 x值数量:3 x值1:3.4 f(X)= 0.330716549275 x值2:-3.4 f(X)= 0.000000025104 x值3:4 f(X)= 0.303015189801

但这就是我所收到的

C:\ Csource> a.exe 输入平均值u:3.489 输入标准偏差:1.203 x值数量:3 x值1:3.4 f(x)=:15086080.000000 x值2:-3.4 f(x)=:15086080.000000 x值3:4 f(x)=:1610612736.000000

2 个答案:

答案 0 :(得分:1)

插入以下行:

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

更改:

const double sigma, mu;

收件人:

double sigma, mu;

更改:

unsigned int x;

收件人:

double x;

normal函数的定义替换为:

double normal(double x, double sigma, double mu)
{   
     double func = 1.0/(sigma * sqrt(2.0*M_PI));
     double t = (x-mu)/sigma;
     return func * exp(-t*t/2);
}

答案 1 :(得分:0)

#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif
#include<math.h>
#include<stdio.h>
#include <stdlib.h>

double normal(double x, double sigma, double mu)
{    
 double func = 1.0/(sigma * sqrt(2.0*M_PI));
 double t = (x-mu)/sigma;
 return func * exp((-0.5*t)* t);
}

我经过一整天的调整之后,终于在上面的代码上工作了,大声笑,C数学可能相当棘手,也感谢您的上述帮助。