SpectralEdge
SpectralEdge

Reputation: 201

How do I convert this bit of C++ code to C#?

Trying to convert some code, but for all my googling I can't figure out how to convert this bit.

    float fR = fHatRandom(fRadius);
    float fQ = fLineRandom(fAngularSpread ) * (rand()&1 ? 1.0 : -1.0);
    float fK = 1;

This bit

(rand()&1 ? 1.0 : -1.0); 

I can't figure out.

Upvotes: 1

Views: 192

Answers (5)

Alex
Alex

Reputation: 7838

It's 1 or -1 with 50/50 chance.

An equivalent C# code would be:

((new Random().Next(0, 2)) == 0) ? 1.0 : -1.0; 

Next(0,2) will return either 0 or 1.

If the code gets called a lot you should store the instance of Random and re-use it. When you create a new instance of Random it gets initialized with a seed that determines the sequence of pseudo-random numbers. In order to have better "randomness" you shouldn't re-initialize the random sequence often.

Upvotes: 7

Piotr Zierhoffer
Piotr Zierhoffer

Reputation: 5139

You can just randomize with 50% chance, as others said.

If you want an exact translation, it would be:

((new Random().Next() & 1 > 0) ? 1.0 : -1.0)

You have to make a boolean out of the first part of conditional expression.

Upvotes: 0

Jirka Hanika
Jirka Hanika

Reputation: 13529

The C++ sample generates a random number, uses its lowest bit and throws away the rest. The lowest bit is then used to pick either -1 or 1.

In C#, the equivalent is as follows.

new Random().Next(0, 2) * 2 - 1

Important: If you do this in a loop, store the instance of Random somewhere and only call Next in the loop, not the constructor again. This is not only a performance optimization. You would otherwise see sequences of identical bits of duration of approximately 100 ms, so calls to the parameterless constructor of Random should be few and far between, ideally one per your app's startup.

Upvotes: 2

RiaD
RiaD

Reputation: 47619

You may use

Random rnd = new Random();
(rnd.NextInt(2) * 2 -1); // 1 or -1

Upvotes: 3

Kent
Kent

Reputation: 598

Either 1.0 or -1.0 with equal chance of either one

rand() generates a number witch is anded with 0x01 i.e. the first bit and depending on if you get a bit or not you get 1.0 or -1.0

Upvotes: 1

Related Questions