Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

c - Random float number

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
", weights[1]);

  float learningRate = 0.1;

  system("PAUSE");
  return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...