zoukankan      html  css  js  c++  java
  • 任意实数范围内的随机数生成原理图解

    实数区间内随机数产生原理 - 图解分析

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     


     

     

     1 //产生[low,high]内的任意随机数,并返回
     2 float randnum(float low,float high)
     3 {
     4 int ret_rnd = 0.0;
     5 
     6 float integerf = 0.0;
     7 float driftf = 0.0;
     8 
     9 if (low >= high)
    10 {
    11 printf("low >= high,rearrange them
    ");
    12 getchar();
    13 return;
    14 }
    15 //---------------------------------------------
    16 
    17 int integer; //整数部分
    18 int decimals; //小数部分
    19 
    20 float diff = high - low;
    21 
    22 integer = (int)(high - low); //取整数部分
    23 
    24 decimals = diff - integer; //取小数部分
    25 //---------------------------------------------
    26 
    27 //1.先计算一个整数偏量值
    28 if (integer > 0)
    29 
    30 integerf= (float)(rand() % integer);
    31 
    32 else 
    33 integerf= 0.0;
    34 
    35 //2.在整数偏量的基础上进行波动
    36 do 
    37 {
    38 driftf = (float)(rand() / RAND_MAX);//产生小数
    39 
    40 driftf *= (rand() % 2 == 0 ? 1 : -1);
    41 
    42 } while ((integerf+driftf<0)||(integerf+driftf>diff));
    43 
    44  
    45 
    46 ret_rnd = low+(integerf + driftf) ;
    47 
    48 return ret_rnd;
    49 
    50 
    51 }
     
     

    -------------------任意开区间,闭区间 随机数生成算法---------------

    srand((unsigned)time(null));

    • (a,b) (rand()%(b-a+1))+a-1
    • [a,b) (rand()%(b-a))+a
    • (a,b] (rand()%(b-a))+a+1
    • [a,b] (rand()%(b-a+1))+a
  • 相关阅读:
    aspx页面,中文乱码解决方案
    使用JSP体验微信公众平台开发模式
    使用微信公众平台“编辑模式”的过程记录
    JAVA刷新网站IP访问量的技术探讨
    301. Remove Invalid Parentheses
    Dungeon Game
    刷题关键点总结-动态规划
    刷题关键点总结-单调栈、单调队列
    coin change
    常用vim命令
  • 原文地址:https://www.cnblogs.com/tsingke/p/4540968.html
Copyright © 2011-2022 走看看