簡體   English   中英

求正態分布的 x 的高斯概率密度

[英]Find the Gaussian probability density of x for a normal distribution

所以,我應該寫一個 function normpdf(x, avg, std)返回x的高斯概率密度 function 對於具有均值avg和標准差std的正態分布, avg = 0std = 1

這是我到目前為止得到的結果,但是當我單擊運行時,我收到以下消息:

Input In [95]
    return pdf
    ^
SyntaxError: invalid syntax

我對那部分做錯了什么感到困惑。

import numpy as np
import math


def normpdf(x, avg=0, std=1) : 
    # normal distribution eq
    exponent = math.exp(-0.5 * ((x - avg) / std) ** 2)
    pdf = (1 / (std * math.sqrt(2 * math.pi)) * exponent)
    return pdf

# set x values 
x = np.linspace(1, 50)

normpdf(x, avg, std)

我在這里添加了括號和math.sqrt

pdf = (1 / (std * math.sqrt(2 * math.pi)) * exponent)

...但后來我收到了這條消息:

TypeError                                 Traceback (most recent call last)
Input In [114], in <cell line: 11>()
      9     pdf = (1/(std*math.sqrt(2*math.pi))*exponent)
     10     return pdf
---> 11 normpdf(x, avg, std)

Input In [114], in normpdf(x, avg, std)
      6 def normpdf(x, avg=0, std=1) : 
      7     #normal distribution eq
----> 8     exponent = math.exp(-0.5*((x-avg)/std)**2)
      9     pdf = (1/(std*math.sqrt(2*math.pi))*exponent)
     10     return pdf

TypeError: only size-1 arrays can be converted to Python scalars

你不需要math模塊。 僅使用numpy函數:

import numpy as np


def normpdf(x, avg=0, std=1):
    exp = np.exp(-0.5 * ((x - avg) / std) ** 2)
    pdf = (1 / (std * np.sqrt(2 * np.pi)) * exp)
    return pdf


x = np.linspace(1, 50)

print(normpdf(x))

上面的代碼將導致:

[2.41970725e-001 5.39909665e-002 4.43184841e-003 1.33830226e-004
 1.48671951e-006 6.07588285e-009 9.13472041e-012 5.05227108e-015
 1.02797736e-018 7.69459863e-023 2.11881925e-027 2.14638374e-032
 7.99882776e-038 1.09660656e-043 5.53070955e-050 1.02616307e-056
 7.00418213e-064 1.75874954e-071 1.62463604e-079 5.52094836e-088
 6.90202942e-097 3.17428155e-106 5.37056037e-116 3.34271444e-126
 7.65392974e-137 6.44725997e-148 1.99788926e-159 2.27757748e-171
 9.55169454e-184 1.47364613e-196 8.36395161e-210 1.74636626e-223
 1.34141967e-237 3.79052640e-252 3.94039628e-267 1.50690472e-282
 2.12000655e-298 1.09722105e-314 0.00000000e+000 0.00000000e+000
 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000
 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000
 0.00000000e+000 0.00000000e+000]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM