Issues with c++ 11 mersenne_twister_engine class

前端 未结 4 1112
谎友^
谎友^ 2021-01-25 11:43

I have been trying to use the c++ 11 mersenne_twister_engine class( http://www.cplusplus.com/reference/random/mersenne_twister_engine/) to generate numbers in the interval [0,1]

4条回答
  •  心在旅途
    2021-01-25 11:58

    In C++, / on integer numbers results in an integer number. For example 11 / 2 results in 5, not 5.5. In the same way a / b is always zero if a < b.

    Your problem is here:

    generator()/generator.max()
    

    generator() and generator.max() both return integers and of course, generator.max() >= generator(), so the result is zero (unless you are very lucky to get the max number in which case the result would be one).

    To fix this, you can simply cast it:

    (double)generator()/generator.max()
    

提交回复
热议问题