You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R或Python中生成指定均值与范围的100个随机值?

Got it! Let's walk through how to generate 100 random numbers with a specific mean and range in both R and Python. I'll share two practical approaches for each language—one that's quick and intuitive, and another that gives you a more natural distribution.

R Language Solutions

Approach 1: Adjust Uniform Random Numbers to Target Mean

This is a simple, no-external-packages method. We start with uniform numbers across your desired range, then shift them to hit your target mean (while keeping values within the range).

# Define your parameters upfront
min_val <- 0    # Lower bound of your range
max_val <- 10   # Upper bound of your range
target_mean <- 5.5  # Desired mean
n <- 100        # Number of random numbers

# Step 1: Generate initial uniform random numbers
set.seed(123) # Use this for reproducible results
rand_nums <- runif(n, min = min_val, max = max_val)

# Step 2: Calculate how much we need to shift the numbers
current_mean <- mean(rand_nums)
adjustment <- target_mean - current_mean

# Step 3: Adjust the numbers and clamp to stay within your range
adjusted_nums <- rand_nums + adjustment
adjusted_nums <- pmax(min_val, pmin(max_val, adjusted_nums))

# Check the results
cat("Adjusted mean:", round(mean(adjusted_nums), 2), "\n")
cat("Min value:", round(min(adjusted_nums), 2), "\n")
cat("Max value:", round(max(adjusted_nums), 2), "\n")

Note: If your adjustment is large, some numbers might get clamped to the min/max boundaries, which can slightly skew the distribution. For a smoother distribution, try the next approach.

Approach 2: Truncated Normal Distribution

For a more natural-looking distribution (closer to bell-shaped), use the truncnorm package to generate numbers that stay within your range and hit your target mean.

# Install the package first if you haven't
# install.packages("truncnorm")
library(truncnorm)

# Define parameters
min_val <- 0
max_val <- 10
target_mean <- 5.5
n <- 100

# Generate truncated normal random numbers
# Adjust the `sd` parameter to control how spread out the numbers are
set.seed(123)
rand_nums <- rtruncnorm(n, a = min_val, b = max_val, mean = target_mean, sd = 2)

# Verify results
cat("Mean:", round(mean(rand_nums), 2), "\n")
cat("Min:", round(min(rand_nums), 2), "\n")
cat("Max:", round(max(rand_nums), 2), "\n")

Tip: If the generated mean isn't exactly your target, tweak the sd value slightly—smaller sd keeps numbers closer to the mean, larger sd spreads them out more.

Python Language Solutions

Approach 1: Adjust Uniform Random Numbers to Target Mean

Just like in R, this method uses NumPy to generate uniform numbers, then shifts them to hit your target mean while respecting the range.

import numpy as np

# Define your parameters
min_val = 0    # Lower range bound
max_val = 10   # Upper range bound
target_mean = 5.5  # Desired mean
n = 100        # Number of random numbers

# Step 1: Generate initial uniform random numbers
np.random.seed(123) # Reproducible results
rand_nums = np.random.uniform(min_val, max_val, n)

# Step 2: Calculate adjustment factor
current_mean = rand_nums.mean()
adjustment = target_mean - current_mean

# Step 3: Adjust numbers and clamp to range
adjusted_nums = rand_nums + adjustment
adjusted_nums = np.clip(adjusted_nums, min_val, max_val)

# Check results
print(f"Adjusted mean: {adjusted_nums.mean():.2f}")
print(f"Min value: {adjusted_nums.min():.2f}")
print(f"Max value: {adjusted_nums.max():.2f}")

Approach 2: Truncated Normal Distribution with SciPy

Use SciPy's truncnorm to generate bell-shaped random numbers within your range. We'll calculate the necessary parameters to align with your target mean.

from scipy.stats import truncnorm
import numpy as np

# Define parameters
min_val = 0
max_val = 10
target_mean = 5.5
n = 100
sd = 2  # Controls spread—adjust as needed

# Calculate `a` and `b` parameters for truncnorm (normalized bounds)
a = (min_val - target_mean) / sd
b = (max_val - target_mean) / sd

# Generate truncated normal random numbers
np.random.seed(123)
rand_nums = truncnorm.rvs(a, b, loc=target_mean, scale=sd, size=n)

# Verify results
print(f"Mean: {rand_nums.mean():.2f}")
print(f"Min: {rand_nums.min():.2f}")
print(f"Max: {rand_nums.max():.2f}")

Pro Tip: If the mean is off by a tiny bit, you can adjust the loc parameter slightly (e.g., loc=target_mean + 0.1) or tweak the sd to get closer to your target.

内容的提问来源于stack exchange,提问作者user37353

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 23:14:06