随机浮点数 [英] Random float number

查看:135
本文介绍了随机浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个函数来得到0之间的伪随机浮动。1包括:

 浮动randomFloat()
{
      浮动R =(浮点)兰特()/(浮点)RAND_MAX;
      返回ř;
}

然而,它总是返回0.563585。同一号码无论多少次,我跑我的控制台应用程序。

编辑:

如果需要的话这是我的整个应用程序:

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;浮动randomFloat()
{
      浮动R =(浮点)兰特()/(浮点)RAND_MAX;
      返回ř;
}INT主(INT ARGC,CHAR *的argv [])
{
  浮X [] = {
        0.72,0.91,0.46,0.03,0.12,0.96,0.79,0.46,0.66,0.72,0.35,-0.16,
        -0.04,-0.11,0.31,0.00,-0.43,0.57,-0.47,-0.72,-0.57,-0.25,
        0.47,-0.12,-0.58,-0.48,-0.79,-0.42,-0.76,-0.77
  };  浮Y [] = {
        0.82,-0.69,0.80,0.93,0.25,0.47,-0.75,0.98,0.24,-0.15,0.01,
        0.84,0.68,0.10,-0.96,-0.26,-0.65,-0.97,-0.03,-0.64,0.15,-0.43,
        -0.88,-0.90,0.62,0.05,-0.92,-0.09,0.65,-0.76
  };  INT输出[] = {
      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
      1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
  };  INT patternCount = sizeof的(X)/的sizeof(int);在  浮动权重[2];
  权重[0] = randomFloat();
  权重[1] = randomFloat();  的printf(%F \\ N,权重[1]);  浮learningRate = 0.1;  系统(暂停);
  返回0;
}


解决方案

您需要调用

 函数srand(时间(NULL));

使用前兰特首次。 时间< time.h中方式>

编辑:正如乔纳森·莱弗勒指出,这是很容易predicted,所以不要尝试使用它的cryprography

I wrote this function to get a pseudo random float between 0 .. 1 inclusive:

float randomFloat()
{
      float r = (float)rand()/(float)RAND_MAX;
      return r;
}

However, it is always returning 0.563585. The same number no matter how many times I run my console application.

EDIT:

Here is my entire application if needed:

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

float randomFloat()
{
      float r = (float)rand() / (float)RAND_MAX;
      return r;
}

int main(int argc, char *argv[])
{
  float x[] = {
        0.72, 0.91, 0.46, 0.03, 0.12, 0.96, 0.79, 0.46, 0.66, 0.72, 0.35, -0.16,
        -0.04, -0.11, 0.31, 0.00, -0.43, 0.57, -0.47, -0.72, -0.57, -0.25,
        0.47, -0.12, -0.58, -0.48, -0.79, -0.42, -0.76, -0.77
  };

  float y[] = {
        0.82, -0.69, 0.80, 0.93, 0.25, 0.47, -0.75, 0.98, 0.24, -0.15, 0.01,
        0.84, 0.68, 0.10, -0.96, -0.26, -0.65, -0.97, -0.03, -0.64, 0.15, -0.43,
        -0.88, -0.90, 0.62, 0.05, -0.92, -0.09, 0.65, -0.76      
  };

  int outputs[] = {
      -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  };

  int patternCount = sizeof(x) / sizeof(int);

  float weights[2];
  weights[0] = randomFloat();
  weights[1] = randomFloat();

  printf("%f\n", weights[1]);

  float learningRate = 0.1;

  system("PAUSE");
  return 0;
}

解决方案

You need to call

srand(time(NULL));

before using rand for the first time. time is in <time.h>.

EDIT: As Jonathan Leffler points out, this is easily predicted, so don't try using it for cryprography.

这篇关于随机浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆