Generating numbers which follow Normal Distribution in Java - 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));
}
}

Related

How to convert two ints (swings, hits) to accuracy

How would I convert swings and hits to accuracy? I know how to calculate the swing/hit ratio but I don't know how to convert it to accuracy.
This is what I've tried:
public double convertToMeleeAccuracy(int swings, int hits) {
try {
double classicHitAccuracy = Double.valueOf(swings - hits); //I know the math for getting the ratio is swings / hits but i don't know how to calculate accuracy.
if (classicwlr < 0) {
return 0.0;
}
return classicwlr;
} catch (ArithmeticException e) {
return 0.0;
}
}
I'm going to try to explain this to you in a way that helped me calculate percentages easily throughout my life.
Let's look at this like so:
Say swings is always 10, so in this scenario, each swing is worth 10% of the accuracy. (because the max accuracy will always be 100%) In that case the function will look something like this:
public class Main {
public static void main(String[] args) {
System.out.println(convertToMeleeAccuracy(3)); // Can be any number you'd like under 10.
}
public static double convertToMeleeAccuracy(int hits) {
int swings = 10;
double percentage = 100.0 / swings;
return hits * percentage;
}
}
In this scenario, the program will output 30.0 which means 30% of the hits have hit.
In the scenario above I only used the number 10 because it's an easy number to work with, here's an example of how this would work with any number of swings:
public class Main {
public static void main(String[] args) {
System.out.println(convertToMeleeAccuracy(22, 21)); // Can be any numbers you'd like.
}
public static double convertToMeleeAccuracy(int swings, int hits) {
double percentage = 100.0 / swings;
return hits * percentage;
}
}
In this scenario, the function will output 95.45454545454547 which is the correct accuracy and you can use any numbers you'd like.
You can also add some checks in the function to make sure hits isn't higher than swings etc..
I hope I helped you understand!

Finding all complex roots of cubic function by using Newton's Method in Java

I've looked everywhere for code I can understand which could help me on my way. I've found one but I'm struggling, so I hope someone could help me.
This is what I want to achieve:
Solve a cubic function (ax^3+bx^2+cx+d) where a,b,c and d are filled
in by the command line when you run it.
I need the roots and complex roots to be found using the Newton's Method. The code I'm struggling with is this, but I don't know if this works and I don't know how I can calculate all 3 roots (even knowing if it has multiplicity 1, 2 or 3).
Any help is appreciated.
import java.util.function.Function;
public class Newton {
static double a = Polynom.geta(); // these are to get the input from the class you run from calling this class to solve the roots
static double b = Polynom.getb();
static double c = Polynom.getc();
static double d = Polynom.getd();
public static void main(String args[]) {
}
private Complex[] sqrt(double x, double y) {
Complex com = new Complex(x,y); // Complex is my class that deals with Complexnumbers, com is supposed to get the value of the root in the end
double tolerance = 1e-11; // tolerance for the error
int iterations = 1, max = 512;
Complex aa = com.pow(3).multiply(a); // These put in the values from input to complex values and fill in the cubic function of ax^3+bx^2+cx+d
Complex bb = com.pow(2).multiply(b);
Complex cc = com.multiply(c);
Complex dd = com.pow(2).multiply(a).multiply(3.0);
Complex ee = com.multiply(2.0).add(com);
Complex function = aa.add(bb).add(cc).add(d,0);
Complex derivative = dd.add(ee);
for(int k = 0; k<3; k++) {
while(iterations<max) {
Complex difference = function.divide(derivative); //difference=fx/dx
com = com.subtract(difference);
if (Math.abs(difference.getReal()) < tolerance && Math.abs(difference.getImaginary()) < tolerance)
return com; // this is where i get an error atm "Cannot convert from Complex to Complex
iterations++;
}
}
}

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.

How to generate Gaussian Noise in 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.

proper way to store large numbers in a variable

I would like to play around with numbers and however elementary, Ive been writing algorithms for the fibonacci sequence and a brute force path for finding prime numbers!
Im not a programmer, just a math guy.
However, a problem I run into quiet often is that a long long, double and floats often run out of room.
If I wanted to continue to work in JAVA, in what way can I create my own data type so that I dont run out of room.
Conceptually, I thought to put 3 doubles together like so,
public class run {
static double a = 0;
static double b = 0;
//static double c = 0;
static void bignumber(boolean x) {
if (x == true && a < 999999999) {
++a;
} else if (x == true && a == 999999999) {
++b;
a = 0;
}
System.out.print(b + "." + a + " \n");
}
public static void main(String[] args) {
while(true) {
bignumber(true);
}
}
}
is there a better way to do this,
I would like to one day be able to say
mydataType X = 18476997032117414743068356202001644030185493386634
10171471785774910651696711161249859337684305435744
58561606154457179405222971773252466096064694607124
96237204420222697567566873784275623895087646784409
33285157496578843415088475528298186726451339863364
93190808467199043187438128336350279547028265329780
29349161558118810498449083195450098483937752272570
52578591944993870073695755688436933812779613089230
39256969525326162082367649031603655137144791393234
7169566988069
or any other number found on this site
I have also tried
package main;
import java.math.BigInteger;
public class run {
BigDecimal a = 184769970321174147430683562020019566988069;
public static void main(String[] args) {
}
}
But it still seems to be out of range
Use BigDecimal (instead of double), and BigInteger (instead of int, long) for that purpose, But you can only work with them by their methods. No operators, can be used.
Used like this:
BigInteger big = new BigInteger("4019832895734985478385764387592") // Strings...
big.add(new BigInteger("452872468924972568924762458767527");
Same with BigDecimal
BigDecimal is the class used in java where you need to represent very large or very small numbers, and maintain precision. The drawbacks are that it is not a primitive, so you can't use the normal math operators (+/-/*/etc), and that it can be a little processor/memory intensive.
You can store large numbers like this:
length
digits[]
and implement your math for them. This is not very complicated. As a hint, to make everything more simple you can store the digits in reverse order. This will make your math simpler to implement - you always add nr[k] with nr[k] and have room for transport for any length numbers, just remember to fill with 0 the shorter one.
In Knuth Seminumeric Algorithms book you can find a very nice implementation for all operations.

Categories

Resources