-1

hi i am trying to write a code for random numbers between -1 and 1 like : 0.9 0.3 0.8 but i can get only numbers like 1 2 3 5 etc using this code

rand()%(max-min + 1) + min

is there any direct function in c++ .if not how can i achieve it

the complete programis :

#include<iostream>
#include<cstdlib>
#include<vector>
using namespace std;

class perceptron{
    public:
        vector <float> weights;
        int max=5,min=1;
        perceptron( float n){
            for( int i=0 ;i< n; i++){

                weights.push_back(rand()%(max-min + 1) + min);
                cout<<weights[i]<<",";
        }
    }
};
int main(){
    perceptron p1(4);
    return 0;
}
kshitij singh
  • 363
  • 2
  • 10
  • 19

1 Answers1

0

Yes, C++ has very good facilities for generating random real numbers.

See this code:

#include <random>
#include <iostream>

int main(int argc, char **argv)
{
    std::random_device randdev;
    std::mt19937 generator(randdev());
    std::uniform_real_distribution<> distrib(-1, 1);
    std::cout << distrib(generator) << '\n';
}

You do need to use a recent version of C++, though (C++11).

juhist
  • 4,210
  • 16
  • 33