写一段a到b之间的符合正态分布的随机数
时间: 2023-05-12 21:07:20 浏览: 83
以下是一段生成符合正态分布的随机数的 Python 代码:
```python
import random
import math
def normal_distribution(mean, std_dev):
u1 = random.random()
u2 = random.random()
z = math.sqrt(-2 * math.log(u1)) * math.cos(2 * math.pi * u2)
return mean + std_dev * z
a = 0
b = 10
mean = (a + b) / 2
std_dev = (b - a) / 6
random_number = normal_distribution(mean, std_dev)
print(random_number)
```
这段代码会生成一个符合正态分布,均值为 (a+b)/2,标准差为 (b-a)/6 的随机数。你可以根据需要修改 a 和 b 的值。
相关问题
写一段正态分布的随机数
下面是一段生成正态分布随机数的 Python 代码:
```python
import random
import math
def normal_distribution(mu, sigma):
while True:
u1 = random.random()
u2 = random.random()
z = math.sqrt(-2 * math.log(u1)) * math.cos(2 * math.pi * u2)
yield mu + sigma * z
generator = normal_distribution(0, 1)
print([next(generator) for _ in range(10)])
```
这段代码使用 Box-Muller 变换生成正态分布随机数,其中 `mu` 和 `sigma` 分别是正态分布的均值和标准差。`normal_distribution` 函数返回一个生成器,每次调用 `next` 方法都会生成一个新的正态分布随机数。上面的代码生成了 10 个随机数并打印出来。
生成一个符合正态分布的随机数的函数 random python
可以使用 Python 标准库中的 random 模块和 NumPy 库中的 random 模块生成符合正态分布的随机数。
使用 Python 标准库中的 random 模块生成符合正态分布的随机数的代码如下:
```python
import random
import math
def generate_normal_distribution(mean, std):
# Box-Muller transform
u1 = random.uniform(0, 1)
u2 = random.uniform(0, 1)
z = math.sqrt(-2 * math.log(u1)) * math.cos(2 * math.pi * u2)
return z * std + mean
```
使用 NumPy 库中的 random 模块生成符合正态分布的随机数的代码如下:
```python
import numpy as np
def generate_normal_distribution(mean, std):
return np.random.normal(mean, std)
```
以上两个函数都可以生成符合正态分布的随机数,其中第一个函数使用了著名的 Box-Muller 变换,适用于生成小批量的随机数,而第二个函数使用了 NumPy 库中的随机数生成函数,适用于生成大批量的随机数。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)