Python中如何生成指定范围内符合函数输出的随机数据集?
Hey there! Let's break down how to generate that dataset you need. The core issue here is expanding the limited 0.0-1.0 range from random.random() to your full mymin-mymax interval, then applying your function to those scaled values. Here's how to do it:
Basic Approach with Python's Built-in random Module
First, we'll map the 0-1 random values to your desired range using a simple formula:x = mymin + random.random() * (mymax - mymin)
This formula takes the 0-1 float, scales it to fit the span of your range, then shifts it to start at mymin. Once we have our x in the right range, we just apply your timestwo(x) function to get the corresponding y value.
Here's a complete code example:
import random # Your target function def timestwo(x): return x * 2 # Function to generate the dataset def generate_custom_dataset(mymin, mymax, num_points): dataset = [] for _ in range(num_points): # Scale random 0-1 value to fit mymin-mymax range x = mymin + random.random() * (mymax - mymin) # Calculate y using your function y = timestwo(x) dataset.append((x, y)) return dataset # Example: Generate 100 points between 5 and 20 my_dataset = generate_custom_dataset(5, 20, 100)
Faster Alternative for Large Datasets with NumPy
If you need to generate thousands or millions of points, using NumPy will be way more efficient than looping with the built-in random module. NumPy's np.random.uniform() lets you generate an array of values directly in your desired range:
import numpy as np def timestwo(x): return x * 2 def generate_numpy_dataset(mymin, mymax, num_points): # Generate all x values at once in [mymin, mymax] x_values = np.random.uniform(low=mymin, high=mymax, size=num_points) # Calculate y values (works with arrays too!) y_values = timestwo(x_values) # Combine into a single dataset array return np.column_stack((x_values, y_values)) # Example: Generate 1000 points between 5 and 20 numpy_dataset = generate_numpy_dataset(5, 20, 1000)
Quick Note for Integer Values
If your use case requires integer x values instead of floats, swap random.random() with random.randint(mymin, mymax) (for the built-in module) or np.random.randint(mymin, mymax+1, size=num_points) (for NumPy) to get whole numbers in your range.
内容的提问来源于stack exchange,提问作者sam

