I want to cast a long value to an int value and if the long value is too big to fit into an int it should just be the the biggest possible int value. My solution looks like that:
long longVar = ...;
int intVar = (int) Math.min(longVar, Integer.MAX_VALUE)
In a more general way (to include the negative maximum) it would be:
long longVar = ...;
int intVar = (int) (longVar < 0 ? Math.max(longVar, Integer.MIN_VALUE) : Math.min(longVar, Integer.MAX_VALUE));
Is there an easier way to do this, like a method in the JRE or something?
An improvement would be
int intVar = (int) Math.min(Math.max(longVar, Integer.MIN_VALUE),
Integer.MAX_VALUE));
Math.max would make [Long.Min,Long.Max] => [Int.Min, Long.Max] and whatever outcome of that, if it is greater than Int.Max will be trimmed down by the outer Math.min to [Int.Min, Int.Max].
I don't know of a ready-to-go method doing this included in java.
The java 8 method Math.toIntExact will throw an exception on overflow. And using that to do this - well, I'd consider it a misuse of exceptions. And probably less efficient than above construct.
If you can use Guava, there is a method that does exactly what you want: static int Ints.saturatedCast(long):
long longVar = ...;
int intVar = Ints.saturatedCast(longVar);
For general interest, there's the Wikipedia article on saturation arithmetic. The Intel MMX instruction set uses saturation arithmetic and I think Intel offer an SDK to allow Java developers to use MMX. I'm not sure if Guava implements its methods using this SDK (probably not).
You can also write some reusable code.
package it.stackoverflow;
public class UtilInt {
public static int getIntMaxMinLong(long longNumber){
int intNumber = 0;
if (longNumber < Integer.MIN_VALUE )
intNumber = Integer.MIN_VALUE;
else if (longNumber > Integer.MAX_VALUE)
intNumber = Integer.MAX_VALUE;
else
intNumber = (int) longNumber;
return intNumber;
}
}
You can call the method in the static way.
package it.stackoverflow;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
int intNewValue = UtilInt.getIntMaxMinLong(224748223647L);
}
}
Hi may i know how can i write a code to generate the alphanumeric code which is look like this HW6KNMQA, CMKQ83JX ? I dont wish to use UUID method. Is there any simple method to generate for this ? ANy help would be appreciated.
What i have done so far;
import org.apache.commons.lang.RandomStringUtils;
public String testing() throws Exception
{
int ID_LENGTH = 10;
String a = RandomStringUtils.randomAlphanumeric(ID_LENGTH);
return a;
}
but i received error
java.lang.NoClassDefFoundError: org/apache/commons/lang/RandomStringUtils
You could use the RandomStringUtils from the Apache project. That being said, you do not seem to require a fixed length value, this, I think, could cause trouble down the line since it might make it harder to identify the value you are after.
If this is not a problem, you could use the Random function to randomly decide the length of the string to generate.
You can use BigInteger.toString(int radix).
Random random = new Random(System.currentTimeMillis());
public void test() {
for (int i = 0; i < 10; i++) {
String n = BigInteger.valueOf(Math.abs(random.nextLong())).toString(32).toUpperCase();
if (n.length() > 8) {
if (n.length() > 10) {
n = n.substring(n.length() - 10);
}
System.out.println(n);
}
}
}
Note that because this is in base 32 you will not see WXYZ but you should see all other characters and digits with equal probability.
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));
}
}
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.
Okay, I implemented this SO question to my code: Return True or False Randomly
But, I have strange behavior: I need to run ten instances simultaneously, where every instance returns true or false just once per run. And surprisingly, no matter what I do, every time i get just false
Is there something to improve the method so I can have at least roughly 50% chance to get true?
To make it more understandable: I have my application builded to JAR file which is then run via batch command
java -jar my-program.jar
pause
Content of the program - to make it as simple as possible:
public class myProgram{
public static boolean getRandomBoolean() {
return Math.random() < 0.5;
// I tried another approaches here, still the same result
}
public static void main(String[] args) {
System.out.println(getRandomBoolean());
}
}
If I open 10 command lines and run it, I get false as result every time...
I recommend using Random.nextBoolean()
That being said, Math.random() < 0.5 as you have used works too. Here's the behavior on my machine:
$ cat myProgram.java
public class myProgram{
public static boolean getRandomBoolean() {
return Math.random() < 0.5;
//I tried another approaches here, still the same result
}
public static void main(String[] args) {
System.out.println(getRandomBoolean());
}
}
$ javac myProgram.java
$ java myProgram ; java myProgram; java myProgram; java myProgram
true
false
false
true
Needless to say, there are no guarantees for getting different values each time. In your case however, I suspect that
A) you're not working with the code you think you are, (like editing the wrong file)
B) you havn't compiled your different attempts when testing, or
C) you're working with some non-standard broken implementation.
Have you tried looking at the Java Documentation?
Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence ... the values true and false are produced with (approximately) equal probability.
For example:
import java.util.Random;
Random random = new Random();
random.nextBoolean();
You could also try nextBoolean()-Method
Here is an example: http://www.tutorialspoint.com/java/util/random_nextboolean.htm
Java 8: Use random generator isolated to the current thread: ThreadLocalRandom nextBoolean()
Like the global Random generator used by the Math class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified. When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention.
java.util.concurrent.ThreadLocalRandom.current().nextBoolean();
Why not use the Random class, which has a method nextBoolean:
import java.util.Random;
/** Generate 10 random booleans. */
public final class MyProgram {
public static final void main(String... args){
Random randomGenerator = new Random();
for (int idx = 1; idx <= 10; ++idx){
boolean randomBool = randomGenerator.nextBoolean();
System.out.println("Generated : " + randomBool);
}
}
}
You can use the following for an unbiased result:
Random random = new Random();
//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;
Note: random.nextInt(2) means that the number 2 is the bound. the counting starts at 0. So we have 2 possible numbers (0 and 1) and hence the probability is 50%!
If you want to give more probability to your result to be true (or false) you can adjust the above as following!
Random random = new Random();
//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;
//For 25% chance of true
boolean chance25oftrue = (random.nextInt(4) == 0) ? true : false;
//For 40% chance of true
boolean chance40oftrue = (random.nextInt(5) < 2) ? true : false;
The easiest way to initialize a random number generator is to use the parameterless constructor, for example
Random generator = new Random();
However, in using this constructor you should recognize that algorithmic random number generators are not truly random, they are really algorithms that generate a fixed but random-looking sequence of numbers.
You can make it appear more 'random' by giving the Random constructor the 'seed' parameter, which you can dynamically built by for example using system time in milliseconds (which will always be different)
you could get your clock() value and check if it is odd or even. I dont know if it is %50 of true
And you can custom-create your random function:
static double s=System.nanoTime();//in the instantiating of main applet
public static double randoom()
{
s=(double)(((555555555* s+ 444444)%100000)/(double)100000);
return s;
}
numbers 55555.. and 444.. are the big numbers to get a wide range function
please ignore that skype icon :D
You can also make two random integers and verify if they are the same, this gives you more control over the probabilities.
Random rand = new Random();
Declare a range to manage random probability.
In this example, there is a 50% chance of being true.
int range = 2;
Generate 2 random integers.
int a = rand.nextInt(range);
int b = rand.nextInt(range);
Then simply compare return the value.
return a == b;
I also have a class you can use.
RandomRange.java
Words in a text are always a source of randomness. Given a certain word, nothing can be inferred about the next word. For each word, we can take the ASCII codes of its letters, add those codes to form a number. The parity of this number is a good candidate for a random boolean.
Possible drawbacks:
this strategy is based upon using a text file as a source for the words. At some point,
the end of the file will be reached. However, you can estimate how many times you are expected to call the randomBoolean()
function from your app. If you will need to call it about 1 million times, then a text file with 1 million words will be enough.
As a correction, you can use a stream of data from a live source like an online newspaper.
using some statistical analysis of the common phrases and idioms in a language, one can estimate the next word in a phrase,
given the first words of the phrase, with some degree of accuracy. But statistically, these cases are rare, when we can accuratelly
predict the next word. So, in most cases, the next word is independent on the previous words.
package p01;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Main {
String words[];
int currentIndex=0;
public static String readFileAsString()throws Exception
{
String data = "";
File file = new File("the_comedy_of_errors");
//System.out.println(file.exists());
data = new String(Files.readAllBytes(Paths.get(file.getName())));
return data;
}
public void init() throws Exception
{
String data = readFileAsString();
words = data.split("\\t| |,|\\.|'|\\r|\\n|:");
}
public String getNextWord() throws Exception
{
if(currentIndex>words.length-1)
throw new Exception("out of words; reached end of file");
String currentWord = words[currentIndex];
currentIndex++;
while(currentWord.isEmpty())
{
currentWord = words[currentIndex];
currentIndex++;
}
return currentWord;
}
public boolean getNextRandom() throws Exception
{
String nextWord = getNextWord();
int asciiSum = 0;
for (int i = 0; i < nextWord.length(); i++){
char c = nextWord.charAt(i);
asciiSum = asciiSum + (int) c;
}
System.out.println(nextWord+"-"+asciiSum);
return (asciiSum%2==1) ;
}
public static void main(String args[]) throws Exception
{
Main m = new Main();
m.init();
while(true)
{
System.out.println(m.getNextRandom());
Thread.sleep(100);
}
}
}
In Eclipse, in the root of my project, there is a file called 'the_comedy_of_errors' (no extension) - created with File> New > File , where I pasted some content from here: http://shakespeare.mit.edu/comedy_errors/comedy_errors.1.1.html
For a flexible boolean randomizer:
public static rbin(bias){
bias = bias || 50;
return(Math.random() * 100 <= bias);
/*The bias argument is optional but will allow you to put some weight
on the TRUE side. The higher the bias number, the more likely it is
true.*/
}
Make sure to use numbers 0 - 100 or you might lower the bias and get more common false values.
PS: I do not know anything about Java other than it has a few features in common with JavaScript. I used my JavaScript knowledge plus my inferring power to construct this code. Expect my answer to not be functional. Y'all can edit this answer to fix any issues I am not aware of.