How to generate Gaussian Noise in Java? - java

I am looking for a Gaussian Noise generator that takes in 2 parameters: mean and variance, and then generates the Gaussian Noise.
During the searching, I find quite a number of such generators for images. However, what I want is a generic generator. I wish to do something like:
myGaussianNoiseGenerator = new GaussianNoiseGenerator(mean, variance);
mySignalWithNoise = mySignal + myGaussianNoiseGenerator.generate();
How may I do this?

De-normalizing the output of Random.nextGaussian() to your needs should be straightforward:
java.util.Random r = new java.util.Random();
double noise = r.nextGaussian() * Math.sqrt(variance) + mean;

You can try this:
Make a new class first called GaussianNoiseGenerator.
public class GaussianNoiseGenerator {
public final int mean;
public final int variance;
public GaussianNoiseGenerator(int mean, int variance) {
this.mean = mean;
this.variance = variance;
//do the math here, and return result
int result = this.mean * this.variance;
//I am not sure of the math, just an example for you
return result;
}
}
then you can use it by:
GaussianNoiseGenerator myGaussianNoiseGenerator = new GaussianNoiseGenerator(56115, 455445);

The noise should probably have a mean of 0, so something like this should work:
import java.util.Random;
...
Random rand = new Random();
mySignalWithNoise = mySignal + rand.nextGaussian()*noiseStandardDeviation;

If by "signal" you mean just double value, then the answer is
Random rnd = new Random();
double signal = (rnd.nextGaussian() - mean) / Math.sqrt(variance);
Where Random is standard class.
Proof
If you group sigma and mu under square with x here
Factor before exponent is irrelevant since distribution can be renormalized.

Related

How can I get full-ranged random float values?

I found that Random#nextFloat returns a value between 0.0 and 1.0.
How can I get a random float value such as -72.0F or 126.232F?
I currently doing like this.
float randomFloat() {
final ThreadLocalRandom random = ThreadLocalRandom.current();
float value = random.nextFloat() * Float.MAX_VALUE;
if (random.nextBoolean()) {
value = 0 - value;
}
return value;
}
Is this right? Is there any other way to do this?
I would suggest generating a bound double and then converting to float:
return Double.valueOf(random.nextDouble(Float.MIN_VALUE, Float.MAX_VALUE)).floatValue();
The nextDouble method has been replaced in Java 8 with a method to produce a stream of doubles. So in Java 8 you would use the following equivalent:
DoubleStream randomDoubles = new Random().doubles(Float.MIN_VALUE, Float.MAX_VALUE);
Double.valueOf(randomDoubles.findAny().getAsDouble()).floatValue();
This is based on a the general idea in the prior answer, but fixes a small bug and shows how to actually write the method using JDK 1.8:
import java.util.Iterator;
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void main(String[] args) {
Test t = new Test();
for (int i = 0; i < 100; i++) {
System.out.println(t.randomFloat());
}
}
final ThreadLocalRandom random = ThreadLocalRandom.current();
Iterator<Double> randomDoubles = random.doubles(-Float.MAX_VALUE,
Math.nextUp((double) Float.MAX_VALUE)).iterator();
float randomFloat() {
return randomDoubles.next().floatValue();
}
}
The code in the question used ThreadLocalRandom, so I did the same. The Random doubles method excludes the upper limit. In order to get the required full range, use as limit the smallest double that is greater than all finite float values. Getting an iterator<Double> seemed simpler and more direct than using findAny etc.

Generating numbers which follow Normal Distribution in Java

I want to generate numbers(randomly) such that the numbers follow the Normal distribution of given mean and variance. How can I achieve this?
It would be better if you can give this in context of Java.
One might look in these answers for help: but they are not precise.
Generate random numbers following a normal distribution in C/C++
Shamelessly googled and taken from: http://www.javapractices.com/topic/TopicAction.do?Id=62
The 'magic' happend inside Random.nextGaussian()
import java.util.Random;
/**
Generate pseudo-random floating point values, with an
approximately Gaussian (normal) distribution.
Many physical measurements have an approximately Gaussian
distribution; this provides a way of simulating such values.
*/
public final class RandomGaussian {
public static void main(String... aArgs){
RandomGaussian gaussian = new RandomGaussian();
double MEAN = 100.0f;
double VARIANCE = 5.0f;
for (int idx = 1; idx <= 10; ++idx){
log("Generated : " + gaussian.getGaussian(MEAN, VARIANCE));
}
}
private Random fRandom = new Random();
private double getGaussian(double aMean, double aVariance){
return aMean + fRandom.nextGaussian() * aVariance;
}
private static void log(Object aMsg){
System.out.println(String.valueOf(aMsg));
}
}

How to split Math work into worker threads Java

I'm developing a Java app that calcuates numbers to powers. I would like to take advantage of my quad core computer, as only one core is being used with this application. I've looked at different tutorials on how to syncronize threads, but I don't really get it. My code is below:
public class Bignum{
public static void main(String[] args){
Random generator = new Random();
long start = System.nanoTime();
Random generator1 = new Random();
for (long i=0; i<9000;i++){
int power = generator1.nextInt (17) + 2;
int power1 = generator1.nextInt (25) + 2;
int power2 = generator1.nextInt (72) + 2;
BigInteger num = BigInteger.valueOf (generator.nextInt (7895) + 1);
BigInteger num1 = BigInteger.valueOf (generator.nextInt (1250) + 1);
BigInteger num2 = BigInteger.valueOf (generator.nextInt (9765) + 1);
BigInteger add = num.pow(power);
BigInteger add1 = num1.pow(power1);
BigInteger add2 = num2.pow(power2);
BigInteger sum = add.add(add1);
}
}
}
So, for example, how could I have one thread do this:
int power = generator1.nextInt (17) + 2;
int power1 = generator1.nextInt (25) + 2;
int power2 = generator1.nextInt (72) + 2;
Another do this:
BigInteger num = BigInteger.valueOf (generator.nextInt (7895) + 1);
BigInteger num1 = BigInteger.valueOf (generator.nextInt (1250) + 1);
BigInteger num2 = BigInteger.valueOf (generator.nextInt (9765) + 1);
Another this:
BigInteger add = num.pow(power);
BigInteger add1 = num1.pow(power1);
BigInteger add2 = num2.pow(power2);
And the last one do this:
BigInteger sum = add.add(add1);
How could I do that? Also, how could I still repeat that 9000 times? Thank you for your help.
In Java 8 parallel maths can be quite elegant. Code below takes advantage of the fact that "+" operation is additive, so values can be summed in any order.
So the code below create a sequence of numbers in parallel and reduces (sums) them in a single thread.
import java.math.BigInteger;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;
import static java.math.BigInteger.valueOf;
import static java.util.concurrent.ThreadLocalRandom.current;
public class Bignum {
public static void main(String[] args) {
Optional<BigInteger> sum = IntStream.range(0, 9000)
.parallel() <-- this enables parallel execution
.mapToObj(value -> {
ThreadLocalRandom generator = current();
int power = generator.nextInt(17) + 2;
int power1 = generator.nextInt(25) + 2;
int power2 = generator.nextInt(72) + 2;
BigInteger num = valueOf(generator.nextInt(7895) + 1);
BigInteger num1 = valueOf(generator.nextInt(1250) + 1);
BigInteger num2 = valueOf(generator.nextInt(9765) + 1);
BigInteger add = num.pow(power);
BigInteger add1 = num1.pow(power1);
BigInteger add2 = num2.pow(power2);
return add.add(add1).add(add2);
})
.reduce(BigInteger::add);
System.out.println(sum.get());
}
}
So i really recommend this book to get started with java multi-threading. It's like the bible of this stuff.
That being said, you're going to need a thread pool to hold your tasks, and youre going to need to make a 'worker' class (which will become the thread) that handles what it needs to do, and properly exits/returns its value.
-Make your thread pool
ExecutorService executor = Executors.newFixedThreadPool(MAX_NUMBER_THREADS_AT_ONCE);
-Make your worker task
public static class WorkerTask implements Runnable {
//member vars if you need em
WorkerTask() {
//initialize member vars if you need to
}
#Override
public void run() {
//do your work here
}
}
-Add tasks to the thread pool like this:
for( each task you need ){
Runnable worker = new WorkerTask( constructor params );
executor.execute(worker);
}
Finally, this leaves two questions:
How do I wait for them to finish?
How do I return a value from a thread?
The fact is that both of these questions have a bunch of ways to solve which might be specific to your problem, but I think in this case you can do something simple. I recommend a global static class variable which will have global scope and be able to be accessed by all threads. Be careful here, dont edit the same values as other threads, so use something like a ConcurrentHashMap, and when a thread has its answer, just add the thread id and its answer to the hashmap. ex: concurrentMap.add(threadId, value);
To wait until all the tasks are done I usually do something like this:
executor.shutdown(); //signal that you want to shutdown executor
while(!executor.isTerminated()){
Thread.sleep(10000); //wait ten seconds
System.out.println("Waiting 10 seconds");
}
// now finally traverse your value map and output your answers
I prefer working with queues for thread input and output, just see the example in the docs: http://download.java.net/jdk7/archive/b123/docs/api/java/util/concurrent/BlockingQueue.html
In general there are 2.5 reasons for using threads to begin with:
In multi cpu systems
when dealing with IO (monitor, mouse, keyboard, sockets, read / write files etc.)
for timers
Assuming you are not doing IO and not need timers, having more threads than your system CPU is going to slow you dowwwwwwwwwwwn

Unique random number for a particular timestamp

I am kind of learning concepts of Random number generation & Multithreading in java.
The idea is to not generating a repeated random number of range 1000 in a particular millisecond (Considering, not more than 50 data, in a multithreaded way will be processed in a millisecond). So that list of generated random number at the specific time is unique. Can you give me any idea as i am ending up generating couple of repeated random numbers (also, there is a considerable probability) in a particular milli second.
I have tried the following things where i failed.
Random random = new Random(System.nanoTime());
double randomNum = random.nextInt(999);
//
int min=1; int max=999;
double randomId = (int)Math.abs(math.Random()* (max - min + 1) + min);
//
Random random = new Random(System.nanoTime()); // also tried new Random();
double randomId = (int)Math.abs(random.nextDouble()* (max - min + 1) + min);
As I am appending the timestamp that is being generated, in a multithreaded environment i see the same ids (around 8-10) that is being generated (2-4 times) for 5000+ unique data.
First, you should use new Random(), since it looks like this (details depend on Java version):
public Random() { this(++seedUniquifier + System.nanoTime()); }
private static volatile long seedUniquifier = 8682522807148012L;
I.e. it already makes use of nanoTime() and makes sure different threads with the same nanoTime() result get different seeds, which new Random(System.nanoTime()) doesn't.
(EDIT: Pyranja pointed out this is a bug in Java 6, but it's fixed in Java 7:
public Random() {
this(seedUniquifier() ^ System.nanoTime());
}
private static long seedUniquifier() {
// L'Ecuyer, "Tables of Linear Congruential Generators of
// Different Sizes and Good Lattice Structure", 1999
for (;;) {
long current = seedUniquifier.get();
long next = current * 181783497276652981L;
if (seedUniquifier.compareAndSet(current, next))
return next;
}
}
private static final AtomicLong seedUniquifier
= new AtomicLong(8682522807148012L);
)
Second, if you generate 50 random numbers from 1 to 1000, the probability some numbers will be the same is quite high thanks to the birthday paradox.
Third, if you just want unique ids, you could just use AtomicInteger counter instead of random numbers. Or if you want a random part to start with, append a counter as well to guarantee uniqueness.
This class will allow you to get nonrepeating values from a certain range until the whole range has been used. Once the range is used, it will be reinitialized.
Class comes along with a simple test.
If you want to make the class thread safe, just add synchronized to nextInt() declaration.
Then you can use the singleton pattern or just a static variable to access the generator from multiple threads. That way all your threads will use the same object and the same unique id pool.
public class NotRepeatingRandom {
int size;
int index;
List<Integer> vals;
Random gen = new Random();
public NotRepeatingRandom(int rangeMax) {
size = rangeMax;
index = rangeMax; // to force initial shuffle
vals = new ArrayList<Integer>(size);
fillBaseList();
}
private void fillBaseList() {
for (int a=0; a<size; a++) {
vals.add(a);
}
}
public int nextInt() {
if (index == vals.size()) {
Collections.shuffle(vals);
index = 0;
}
int val = vals.get(index);
index++;
return val;
}
public static void main(String[] args) {
NotRepeatingRandom gen = new NotRepeatingRandom(10);
for (int a=0; a<30; a++) {
System.out.println(gen.nextInt());
}
}
}
If I understand your question correctly, multiple threads are creating their own instances of Random class at the same time and all threads generate the same random number?
Same number is generated, because all random instances where created at the same time, i.e. with the same seed.
To fix this, create only one instance of Random class, which is shared by all threads so that all your threads call nextDouble() on the same instance. Random.nextDouble() class is thread safe and will implicitly update its seed with every call.
//create only one Random instance, seed is based on current time
public static final Random generator= new Random();
Now all threads should use the same instance:
double random=generator.nextDouble()

to find the angle for cosine! vector products

I am looking for an answer to find an angle-alpha for cosine.
cos(alpha)=RT(vector).R(vector)/(modulus)RT(vector).(modulus)R(vector)
then I should need to find the angle alpha.
public double dot1(double[] vectorA, double[] vectorB){
double[] vecPro;
vecPro = new double[2];
vecPro[0] = vectorA[0]*vectorB[0];
vecPro[1] = vectorA[1]*vectorB[1];
return 0;
}
this code is just an sample I did so far! for the dot product of RT(vector).R(vector).
hmm is that correct that I did, because I am new to java language.
That doesn't calculate dot product. This does
public double dot1(double[] vectorA, double[] vectorB){ //if they're from R^2
double[] vecPro = new double[2];
vecPro[0] = vectorA[0]*vectorB[0];
vecPro[1] = vectorA[1]*vectorB[1];
//you did fine up to here
//But, you should return the result (sum of components products) #see wiki link
//0 surely isn't the result you want for two arbitrary vectors
return vecPro[0] + vecPro[1];
}
It is hard to figure out what you are really asking, but the place to find implementations of the trigonometric functions like sine, cosine and tangent is the java.lang.Math class.

Categories

Resources