I have a simple java program that creates an array of random numbers. I am using rJava to call this program and create an R object. I know how to create random numbers in R ... I am trying to reproduce the results of a complicated java program exactly, which requires I use the same random numbers. Here is the java:
import java.util.Random;
public class rJava
{
public static void main(String[] args)
{
createRan();
}
public static double[] createRan()
{
int numSims = 100000;
int m_RandomSeed = 1234567;
Random m_Rnd = new Random(m_RandomSeed);
double[] randoms = new double[100000];
for(int i=0; i < numSims; i++)
{
randoms[i] = m_Rnd.nextDouble();
}
return randoms;
}
}
rJava seems to be working fine for me ... I use the following commands in R and an object called "rans" with 100000 random numbers is created.
library(rJava)
.jinit()
obj <- .jnew("rJava")
rans <- .jcall(obj, "[D", "createRan")
My problem is I went to change the size of the array for testing purposes to something more manageable, like 10 random numbers instead of 100,000. I saved and recompiled rJava.java, and re-ran the R code above. It still created an array of 100,000 numbers. I rebooted my computer and tried again ... still 100,000. I would ultimately like to pass a parameter into the java code to choose the number of random numbers to generate but would like to understand what is going on here first. I know very little about Java, is there some place where the initial state of rJava.java is stored and is being called from? As I said I have recompiled the class file so I would not the "original" would be overwritten.
Thanks
Related
I'm trying to distribute a system and I need to use nextGaussian() from the Random Java class. The only way I found to break the data dependency a unique seed creates was using multiple seeds, thus, creating multiple randoms.
Let's forget about the context of my problem, I just want to know how well normalized is using multiple Random instances compared to using only one instance. In other words... How random is this genNew compared to genSame?
The code:
public double[] genNew(int lim, long seed)
{
double[] rand = new double[lim];
for(int i = 0; i < lim; i++)
{
//A random for each iteration.
Random r = new Random(i*seed);
rand[i] = r.nextGaussian();
}
return rand;
}
public double[] genSame(int lim, long seed)
{
double[] rand = new double[lim];
//A random for all iterations
Random r = new Random(seed);
for(int i = 0; i < lim; i++)
rand[i] = r.nextGaussian();
return rand;
}
The results I get are very different when I apply both arrays to my code. I just can't explain why.
EDIT: I know this won't generate the same arrays, it is just that when using a big ammount of normalized randoms to calculate a number, both numbers should be close (because of the normalization), but they aren't.
I found a way to generate adecuate numbers and break the data dependency.
I don't understand why this factor works, but it does. I found it by chance and I've done almost a million millions tests on it and keeps working without failing.
If someone understands why this works, please tell:
Random r = new Random(seed * 43112609)
This number is a prime. That's the only clue I have, but still, I really can't understand why it works.
I've made a program that generates a random number but every time it gives back 0.0
Program:
import java.util.*;
public class RandomNumber {
public static void main(String args[]){
double QuantityColors = 5;
double Mastermind = 0;
Random(QuantityColors, Mastermind);
System.out.println(Mastermind);
}
public static double Random(double QuantityColors, double Mastermind){
Mastermind = Math.random();
Mastermind = Mastermind * QuantityColors;
Mastermind = (int) Mastermind;
return Mastermind ;
}
}
I've been searching where the problem is, but the problem is in the return.
a) you are doing nothing with the result of "Random".
b) you can not modify Java argument. See change a functions argument's values?
First of all, you can use a builtin function to generate a next integer with a certain upper bound: Random.nextInt(int). For instance:
Random rand = new Random();
int masterMind = rand.nextInt(QuantityColors);
Instead of writing a Random method yourself.
It is nearly always better to use builtins since these have been tested extensively, are implemented to be rather fast, etc.
Next you seem to assume that Java uses pass-by-reference. If you perform the following call:
Random(QuantityColors, Mastermind);
Java will make a copy of the value of MasterMind. Setting the parameter in a method has no use. The only way to set a value - not encapsulated in an object - is by returning value. So:
MasterMind = Random(QuantityColors, Mastermind);
To make a long story short: the method does not return 0, you simply don't do anything useful with it.
A better solution would thus be to drop the Random method and use:
import java.util.*;
public class RandomNumber {
public static void main(String args[]){
int quantityColors = 5;
Random rand = new Random();
int mastermind = rand.nextInt(QuantityColors);
System.out.println(mastermind);
}
}
Further remarks
In your random method:
public static double Random(double QuantityColors, double Mastermind){
the MasterMind parameter is rather useless since you immediately set it with another value, so you better remove it and use a local variable instead.
Furthermore Java standards say that the name of classes, interfaces, etc. start with an uppercase; the names of methods and variables with lowercase.
Finally it is unclear why you use doubles since all the values you calculate are clearly integral.
It looks like your code would work if you wrote
Mastermind = Random(QuantityColors, Mastermind);
...because Java is pass by value, so calling a function will not change the variable you passed in.
Summary: I need a function based on the output. The problem is
connecting Eclipse or a Java code with another software.
I'm studying Physics. I needed a code that works the following way:
first, it declares a random number n;
then it outputs a "winner" number (based on some rules; the code
itself is irrelevant now I think), 20 times (but should be more,
first I need something to record the values, though).
I have n and 20 other numbers which are each between 1 and n (including 1 and n). I want, after compiling the code once, to see the 20 values, how they are distributed (for example, are they around one particular number, or in a region, is there a pattern (this is based on the rules, of course)).
The problem is, I'm only familiar with basic Java (I used eclipse), and have no clue on how I should register for example 2000 instead of the 20 numbers (so for an n number the code should print 2000 or more numbers, which should appear on a function: domain of the function is 1, 2, ..., n, and range is 0, 1, ..., 2000, as it might happen that all 2000 numbers are the same). I thought of Excel, but how could I connect a Java code with it? Visual interpretation is not necessary, although it would make my work easier (I hope, at least).
The code:
import java.util.Random;
public class korbeadosjo {
public static void main(String Args[]){
Random rand = new Random();
int n = (rand.nextInt(300)+2);
System.out.println("n= " + n);
int narrayban = n-1;
int jatekmester = n/2;
int jatekmesterarrayban = jatekmester-1;
System.out.println("n/2: " + jatekmester);
for(int i=0; i<400; i++){
int hanyembernelvoltmar = 1;
int voltmar[] = new int[n];
voltmar[jatekmesterarrayban]=1;
int holvan=jatekmester;
int holvanarrayban = holvan-1;
fori: for(;;){
int jobbravagybalra = rand.nextInt(2);
switch(jobbravagybalra){
case 0: //balra
if(holvanarrayban ==0){
holvanarrayban = narrayban;
}else {
--holvanarrayban;
};
if(voltmar[holvanarrayban]==0){
voltmar[holvanarrayban] =1;
++hanyembernelvoltmar;
}
break;
case 1: //jobbra
if(holvanarrayban == narrayban){
holvanarrayban = 0;
} else {++holvanarrayban;};
if(voltmar[holvanarrayban]==0){
voltmar[holvanarrayban]=1;
++hanyembernelvoltmar;
}
break;
}if(hanyembernelvoltmar==n){
System.out.println(holvanarrayban+1);
break fori;
}}}}}
basic Java (I used eclipse)
Unrelated.
I could only find two prompts in your question:
How to create statistics from output of Java code?
You are likely not wanting to get the output alone. Use those numbers in your Java program to find what you want and output it.
How did you store 2000 values? An array, list, queue...? So also iterate on that data structure and generate the statistics you need.
I thought of Excel, but how could I connect a Java code with it?
There is this site.
Okay
I have The problem that i want to generate 64 numbers between 0 and 1 (that means 0 or 1)
the function i have currently is:
public static int randNr(int max) {
Random r = new Random();
int o = r.nextInt(max);
return o;
}
But it always returns 0.
Is there any way to make that it generates also a 1 ?
EDIT:
the function is located in a different java file than when i calling it!
Two issues:
1) nextInt(max); generates a number from 0 and up to but not including max. My guess is that you're passing 1 as max. Pass 2 and all will be well.
2) Creating a new generator object each time ruins the statistical properties of the generator. You should create one Random instance and (i) either pass into the function or (ii) have the instance stored as a member variable.
This function works fine. You are probably calling it with the wrong arguments. It should be:
randNr(2)
Why? Because it's using the Random#nextInt(max) method, which will return a random integer in the range [0, max-1] (including 0 and max-1).
Note: It's not recommended to create a new Random object each time you call the function. One solution would be to declare the Random object as an static member of the class:
public class Test
{
private static Random r = new Random();
// ...
}
Another solution would be to use the static method Math.random()1:
int o = (int) Math.round(Math.random());
1: Could someone confirm if this method is faster than the OP's one?
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have been trying for weeks in this project where I have to make one class that generates 500 random numbers from 1-250 and in a second class I have to inherit the first class properties and write all those numbers in a text file but when I have being having problems getting the properties and work with it and I haven't found a way to do it online.
My First class is
import java.util.Random;
public class GenKeys {
public static void random(){
for (int i = 0; i < 250; i++) {
int x = (int) (Math.random() * 100);
}
}
}
and my second code is
import java.util.Random;
import java.io.*;
import java.lang.*;
public class MainProg extends GenKeys{
public static void main(String[] args){
public static void random(){
try {
BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));
out.write( x + System.getProperty("line.separator"));// when i compile the x is not found!!!
out.close();
} catch (IOException e) {
System.out.print(e);
}
}
How can I make the two classes work together?
What am i doing Wrong ?
You are using inheritance instead of just using an instance of GenKeys in MainProg
You keep overwriting your random values, since you only use a single variable x, when you should be using e.g. an array
You create 250 values in range [0..99] instead of 500 values in range [1..250]
You don't store or return anything from your random() method
and i havent found a way to do it online.
I'm not sure you've looked hard enough.
How to get your code working
Firstly, you want to change the type and name of your method to an int.
public static int randomNum()
Then, remove the loop from the code, and just return the random number generated:
return (int)Math.Random() * 100; //By the way there is a Random class.
In the random method, you want the loop:
for(int x = 0; x < 250; x++)
{
BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));
out.write( randomNum() + System.getProperty("line.separator"));
}
out.close();
The various issues with your code
You're mis-using inheritance here. Your class is not a type of GenKey. It simply uses it, so it should be a field in your class.
Secondly, a method can only return one value, or one object. It can not return 250 numbers as is. You're assigning 250 numbers to x. This is only going to store the last number generated.
I don't think this is right approach. you need another class, for example KeyWriter to inherit from GenKeys. let it use GenKeys method random (it doesn't need to be static)
also, your random method is wrong, you only generate 250 keys instead of 500, and they are not from 0 to 250.
my solution is:
1) inherit KeyWriter from GenKeys
2) modify random to return only 1 generated number using nextInt
3) use cycle inside KeyWriter to call random 500 times and write those values into a file
4) use KeyWriter class inside you main method
I don't post the actual solution, cause it looks like you're doing your homework.
Well, somethings aren't correct here, but the weirdest of all is that you made the random() function a void.
void random()
Where X goes to? You just create a new int, but do nothing about it.
Besides this, there are other problems, as other folks mentioned around.
I'd recommend you to read about function in Java, especially about the difference between int and void.
Some problems (and comments) I see of the bat:
x is not an instance field and is not stored anywhere thus how can it be accessible from the child class.
Like others have said x is being overwritten with each iteration of your for loop.
Why is the mainProg.random() method declared inside of the mainProg.main() method?
I dont think inheritance is the way to go unless it is absolutely required for this project. Why not just make an instance of your random class inside the main method of the mainProg class?
If you want to use inheritance I believe a call to super.random() will be necessary inside of the mainProg.random() method.(Please someone confirm this. Im not 100% sure)
If it was me I would do something along the lines of this in my GenKeys.random() method:
public int[] random() {
int[] keys = new int[500];
for(int i = 0; i < 500; ++i)
{
keys[i] = (int) (Math.random() * 100);
}
return keys;
}
This code creates and returns an array of 500 keys. NOT in the range of 1-250. See here for that: How do I generate random integers within a specific range in Java?
Hopefully that will get you started on the right track.
x is the local variable of random().
so you can't directly access local variable out side the class.
And you are trying to generate 500 random no. between 1-250 so change the for loop in first class
for (int i = 0; i < 500; i++){
.....
}