Gasper Gulotta
Gasper Gulotta

Reputation: 159

Converting C++ code with pointers into a Java equivalent

So I'm trying to convert this bit of code to use in my Java program. However, it has a pointer and I'm not sure what would be the best way of translating that into Java.

/**
* 32-bit Multiplicative Congruential Pseudo Random Number Generator
* Microsoft Visual C++ Version
*/
#include <math.h>
/**
* The seed used by randomNumberGenerator.
*/
long gv_lRandomNumberSeed;
/**
* Returns a random number between 0.0 and 1.0.
* plSeed - Pointer to the seed value to use.
*/
double randomNumberGenerator( long* plSeed ) {
double dZ;
double dQuot;
long lQuot;
dZ = ( *plSeed ) * 16807;
dQuot = dZ / 2147483647;
lQuot = ( long ) floor( dQuot );
dZ -= lQuot * 2147483647;
( *plSeed ) = ( long ) floor( dZ );
return ( dZ / 2147483647 );
}

I need to be able to use the above number returned in this function:

/**
* Returns a random variate from an exponential probability
* distribution with the given mean value of dMean.
*/
double exponentialRVG( double dMean ) {
return ( -dMean * log( randomNumberGenerator( &gv_lRandomNumberSeed 
) ) );
}

And be able to enter a value for dMean and get a value in return..

Any help?

(I know a lot of people get angry about poorly posted questions on this site, please try and refrain from the negatively and help me to ask the question better if that is the case)

Upvotes: 0

Views: 181

Answers (5)

James Holderness
James Holderness

Reputation: 23001

That pointer is basically just the C equivalent of a reference parameter. You can achieve the same thing in Java in a number of ways. Have a look at the answers in the question below:

Can I pass parameters by reference in Java?

Upvotes: 0

Andy Thomas
Andy Thomas

Reputation: 86391

Choices include:

  • Place the seed as a field in the same class as the method randomNumberGenerator().
  • Pass the seed in a mutable object parameter to randomNumberGenerator().
  • Return the seed in an object that contains both the new value and the new seed.

Java's Random class uses the first approach. It's the easiest for callers of the method.

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234795

The pointer is being used to update the value of an argument. I'd suggest reorganizing the code to avoid using such an argument (and directly access a class variable gv_lRandomNumberSeed). The rest of the code translates fairly directly into Java (if you're familiar with Java's Random class).

Oh, and please get rid of the Hungarian notation when you port.

Upvotes: 1

Adrian Panasiuk
Adrian Panasiuk

Reputation: 7343

The pointer is used to make plSeed an inout variable.

As you will already be putting randomNumberGenerator into some class, you should promote the function parameter plSeed to a field of that class.

Upvotes: 2

akhil
akhil

Reputation: 732

Use JNI(Java Native Interface) technology. With JNI, you can call the C function from java.

Upvotes: 0

Related Questions