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

如何使用PCG随机数生成库生成指定范围的浮点数?

Generating Fixed-Range Floating-Point Numbers: From rand() to PCG

Let's start with the basics—you can use the standard library's rand() function to generate floats in a fixed range, but honestly, it's the least ideal option out there. Its randomness quality is pretty poor, and it's prone to bias if not handled carefully. Here's what that implementation looks like:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

float randoms(float min, float max) {
    return (float)(rand())/RAND_MAX*(max - min) + min;
}

int main() {
    srand((unsigned int)time(0));
    printf("%f\n",randoms(-100.001, 100.001));
    return 0;
}

I scoured the web for working examples of generating fixed-range floats with the PCG random number library and came up empty, so I wanted to share my own practical implementation here.

Before switching to PCG, I used arc4random for this task, but PCG has a huge advantage: it's far more concise and doesn't come with any messy dependencies. Here's how you can do it with PCG:

#include <stdio.h>
#include <stdint.h>
#include <time.h>
#include "pcg_basic.h"

float pcg_fixed_range_float(float min, float max) {
    // Generate a 32-bit unsigned random integer using PCG
    uint32_t random_uint = pcg32_random();
    
    // Normalize the integer to a float in the [0, 1) range
    // Using UINT32_MAX + 1.0f ensures we don't hit exactly 1.0, avoiding overflow into max
    float normalized = (float)random_uint / (UINT32_MAX + 1.0f);
    
    // Scale and shift to the desired [min, max) range
    return normalized * (max - min) + min;
}

int main() {
    // Initialize the PCG generator with a time-based seed and unique sequence ID
    pcg32_random_t rng;
    pcg32_srandom(time(NULL), (intptr_t)&rng);
    
    // Example: Generate a float between -100.001 and 100.001
    printf("%f\n", pcg_fixed_range_float(-100.001, 100.001));
    
    return 0;
}

A quick heads-up: Make sure you have the PCG library properly set up (include the necessary header files and link against the library during compilation). This implementation avoids the bias issues common with rand(), and PCG's statistical properties are significantly better for most applications that require reliable randomness.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:56:20