【问题标题】:Normal Distribution Functions正态分布函数
【发布时间】:2013-01-14 21:17:46
【问题描述】:

这是编写正态分布函数http://en.wikipedia.org/wiki/Normal_distribution 的正确方法还是我应该使用 pow 函数?我真的很困惑,所以非常感谢您的帮助:)

#include <stdio.h>
#define _USE_MATH_DEFINES 
#include <math.h>
#include <stdlib.h>
int main()
{
double u,s, N, x1,math1, math2, math3,n, v, x;

printf("Enter Mean: ");
scanf("%lf", &u);
printf("Enter Standard Deviation: ");
scanf("%lf", &s);
printf("Enter Number Of Inputs: ");
scanf("%lf", &N);

    for (v=1; v<=N; v++)
    {
    printf("Enter Value: ");
    scanf("%lf", &x);
    n=(-1/2);
    printf("f(x)= ");
    math1 =1/(s*sqrt(2*M_PI));
    math2= (x-u)/s * (x-u)/s;
    math3= M_E * exp(n);
    x1 = math1 * exp(math3)*exp(math2);
    printf("%lf  \n", x1);
    }
system("Pause");
 }

【问题讨论】:

  • 理想情况下,您应该在同一个函数中混合来自用户的输入和输出。
  • 非常接近 stackoverflow.com/questions/2328258/… 的副本 - cmets 中甚至有一些关于为什么不应该使用 pow() 的讨论。
  • -1/2 - 这不是你想的那样。

标签: c


【解决方案1】:

阅读您的代码太难了,但我可以看出它是错误的。这是一个简短的版本:

double twopi = 8.0 * atan(1.0); // preferable to using M_PI
double x = ..., sigma = ..., mu = ...;
double y = (1.0 / (sigma * sqrt(twopi))) *
    exp(-(x - mu)*(x - mu) / (2.0 * sigma * sigma));

请注意我如何将数学公式直接转换为 C 中的表达式...这使得验证代码是否正确变得容易。当你使用一堆临时变量math1math2math3...

请记住:exp() 与数学中的对应物 exp 相同。所以exp(x) 是 ex。一旦意识到这一点,您就会在代码中看到错误。

【讨论】:

  • 感谢您的精彩回答!我认为您在“(1.0”之前的第一个结尾缺少“)”
猜你喜欢
  • 2020-09-08
  • 1970-01-01
  • 2013-01-28
  • 2015-08-22
  • 2019-05-18
  • 2013-11-04
  • 2023-03-26
  • 2013-11-16
相关资源
最近更新 更多