I am trying to convert my float value into Integer, but I cannot convert it. It says cannot find symbol. Are there any ways to do this.
This is my java code:
float upper = 999999;
float lower = 100000;
Integer ReceiptNo = 0;
Random rnd = new Random();
ReceiptNo = Math.round((Math.floor( (upper - lower + 1) * rnd() ) )) + lower;
This is my vb code:
Dim upper As Single = 999999 'Set the upper limit of random number.
Dim lower As Single = 100000
Dim ReceiptNo As Integer = 0
Randomize() 'Need to randomise the random number or else the number generated is always the same
ReceiptNo = CInt(Math.Floor((upper - lower + 1) * Rnd())) + lower
I am trying to reuse the vb code in java. Thank you.
rnd is an instance variable, not a method, so you can't write rnd().
You can write :
ReceiptNo = (int)(Math.round((Math.floor( (upper - lower + 1) * Math.random() ) )) + lower);
I'm not sure what Rnd() does in VB, but if it produces a random double between 0 and 1, that's what Math.random() does.
It seems that should be rnd.nextFloat() instead of rnd()
http://docs.oracle.com/javase/7/docs/api/java/util/Random.html
Dim prng As New Random 'do NOT put this in a method
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim upper As Integer = 999999 + 1 'Set the upper limit of random number.
Dim lower As Integer = 100000
Dim ReceiptNo As Integer = prng.Next(lower, upper) 'the upper is exclusive
End Sub
rnd here is an object of the class Random. Objects can't be used as rnd().
The correct code should be ReceiptNo = Math.round((Math.floor( (upper - lower + 1) * Math.random() ) )) + lower;
For more learning on java classes and objects here is good http://www.tutorialspoint.com/java/java_object_classes.htm
Use Math.random() instead of rnd().
You need to cast the value from Math.round (it's returning float) to int
ReceiptNo = (int) (Math.round((Math.floor( (upper - lower + 1) * Math.random() ) )) + lower);
Related
I need to generate random real numbers in the range [-0.5, 0.5], both bounds inclusive.
I found various ways to generate similar ranges, like
-0.5 + Math.random()
But the upper bound is always exclusive, I need it inclusive as well. 0.5 must be inside the range.
One way to achieve this would be to create random int from -500 to 500 and then divide it by 1000.
int max = 500;
int min = -500;
int randomInt = rand.nextInt((max - min) + 1) + min;
float randomNum = randomInt / 1000.00f;
System.out.println(randomNum);
You can change the precision by adding and removing zeros from the integer boundaries and the divisor. (eG: create integers from -5 to +5 and divide by 10 for less precision)
A disadvantage of that solution is that it does not use the maximum precision provided by float/double data types.
I haven't seen any answer that uses bit-fiddling inside the IEEE-754 Double representation, so here's one.
Based on the observation that a rollover to a next binary exponent is the same as adding 1 to the binary representation (actually this is by design):
Double.longBitsToDouble(0x3ff0000000000000L) // 1.0
Double.longBitsToDouble(0x3ffFFFFFFFFFFFFFL) // 1.9999999999999998
Double.longBitsToDouble(0x4000000000000000L) // 2.0
I came up with this:
long l = ThreadLocalRandom.current().nextLong(0x0010000000000001L);
double r = Double.longBitsToDouble(l + 0x3ff0000000000000L) - 1.5;
This technique works only with ranges that span a binary number (1, 2, 4, 8, 0.5, 0.25, etc) but for those ranges this approach is possibly the most efficient and accurate. This example is tuned for a span of 1. For ranges that do not span a binary range, you can still use this technique to get a different span. Apply the technique to get a number in the range [0, 1] and scale the result to the desired span. This has negligible accuracy loss, and the resulting accuracy is actually identical to that of Random.nextDouble(double, double).
For other spans, execute this code to find the offset:
double span = 0.125;
if (!(span > 0.0) || (Double.doubleToLongBits(span) & 0x000FFFFFFFFFFFFFL) != 0)
throw new IllegalArgumentException("'span' is not a binary number: " + span);
if (span * 2 >= Double.MAX_VALUE)
throw new IllegalArgumentException("'span' is too large: " + span);
System.out.println("Offset: 0x" + Long.toHexString(Double.doubleToLongBits(span)));
When you plug this offset into the second line of the actual code, you get a value in the range [span, 2*span]. Subtract the span to get a value starting at 0.
You can adjust the upper bound by the minimal value (epsilon) larger than the maxium value you expect. To find the epsilon, start with any positive value and make it as small as it can get:
double min = -0.5;
double max = 0.5;
double epsilon = 1;
while (max + epsilon / 2 > max) {
epsilon /= 2;
}
Random random = ThreadLocalRandom.current();
DoubleStream randomDoubles = random.doubles(min, max + epsilon);
Edit: alternative suggested by #DodgyCodeException (results in same epsilon as above):
double min = -0.5;
double max = 0.5;
double maxPlusEpsilon = Double.longBitsToDouble(Double.doubleToLongBits(max) + 1L)
Random random = ThreadLocalRandom.current();
DoubleStream randomDoubles = random.doubles(min, maxPlusEpsilon);
Given HOW GOD SPIDERS answer, here is a ready to use function :
public static double randomFloat(double minInclusive, double maxInclusive, double precision) {
int max = (int)(maxInclusive/precision);
int min = (int)(minInclusive/precision);
Random rand = new Random();
int randomInt = rand.nextInt((max - min) + 1) + min;
double randomNum = randomInt * precision;
return randomNum;
}
then
System.out.print(randomFloat(-0.5, 0.5, 0.01));
#OH GOD SPIDERS' answer gave me an idea to develop it into an answer that gives greater precision. nextLong() gives a value between MIN_VALUE and MAX_VALUE with more than adequate precision when cast to double.
double randomNum = (rand.nextLong() / 2.0) / Long.MAX_VALUE;
Proof that bounds are inclusive:
assert (Long.MIN_VALUE/2.0)/Long.MAX_VALUE == -0.5;
assert (Long.MAX_VALUE/2.0)/Long.MAX_VALUE == 0.5;
Random.nextDouble gives a value in the range of [0, 1]. So to map that to a range of [-0.5, 0.5] you just need to subtract by 0.5.
You can use this code to get the desired output
double value = r.nextDouble() - 0.5;
The following code is only producing a 0 ;-;
What am I doing wrong?
public class RockPaperSci {
public static void main(String[] args) {
//Rock 1
//Paper 2
//Scissors 3
int croll =1+(int)Math.random()*3-1;
System.out.println(croll);
}
}
Edit, Another Poster suggested something that fixed it.
int croll = 1 + (int) (Math.random() * 4 - 1);
Thanks, everyone!
You are using Math.random() which states
Returns a double value with a positive sign, greater than or
equal to 0.0 and less than 1.0.
You are casting the result to an int, which returns the integer part of the value, thus 0.
Then 1 + 0 - 1 = 0.
Consider using java.util.Random
Random rand = new Random();
System.out.println(rand.nextInt(3) + 1);
Math.random() generates double values between range - [0.0, 1.0). And then you have typecasted the result to an int:
(int)Math.random() // this will always be `0`
And then multiply by 3 is 0. So, your expression is really:
1 + 0 - 1
I guess you want to put parenthesis like this:
1 + (int)(Math.random() * 3)
Having said that, you should really use Random#nextInt(int) method if you want to generate integer values in some range. It is more efficient than using Math#random().
You can use it like this:
Random rand = new Random();
int croll = 1 + rand.nextInt(3);
See also:
Math.random() versus Random.nextInt(int)
All our mates explained you reasons of unexpected output you got.
Assuming you want generate a random croll
Consider Random for resolution
Random rand= new Random();
double croll = 1 + rand.nextInt() * 3 - 1;
System.out.println(croll);
public static double random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
int croll =1+(int)Math.random()*3-1;
eg
int croll =1+0*-1;
System.out.println(croll); // will print always 0
Say i have five variables a,b,c,d and e which are all assigned a random number from five different ranges corresponding to to the five variables a to e.
Is there a way to assign a sixth variable say x, that chooses a random number from a range with upper value equal to the total of a+b+c+d+e?
for example, say :-
a=5 (range 0-10)
b=1043 (range 0-2000)
c=37 (range 0-38)
d=2 (range 0-100)
e=20 (range 5-30)
then x = (random number) (range 5- 1107)
Thanks for any assistance
You can use
Min + (int)(Math.random() * ((Max - Min) + 1))
Where Min = a and Max = a+b+c+d+e
From java.util.Random:
Random rand = new Random();
rand.nextInt(X);
//returns an `int` in range: [0,X)
So, if you have a, b, ..., n, to get a number in between 0 and the sum of the variables, we do:
rand.nextInt(a + b + ... + n + 1); //returns an `int` in range [0, sum(a,b,...,n)]
As other users have suggested, you can also use Math.random(); however, Math.random() returns a double in range: [0,1). So, if you have min = 0, max = 9, and want a number between [0,9], then you need:
Min + (int)(Math.round((Math.random() * (Max - Min))))
//need to cast to int since Math.round(double returns a long)
or you could do:
Min + (int)(Math.random() * (Max - Min + 1))
Edit: I missunderstood your problem, but you just need to sum each var and do the same thing. Some answers already showed that.
It is just a algorithm problem.
int lra = 0; // lower range of a
int ura = 10; // upper range of a
int lrb = 0;
int urb = 2000;
// a couple of ranges for each var...
int a = lra + ((int) (Math.random() * (ura - lra)));
// the same for each var...
int lrs = lra + lrb + ...; // sum of lower ranges...
int urs = ura + urb + ...; // sum of upper ranges
int x = lrs + ((int) (Math.random() * (urs - lrs)));
Something like this should do the job
Random generator = new Random();
generator.setSeed(System.currentTimeMillis());
long range = a+b+c+d+e;
long fraction = (long)(range * generator.nextDouble());
randomNumber = (int)(fraction);
I need to make a random number between 1 and 20, and based on that number (using "If - Then" statements), I need to set the image of an ImageView.
I know that in Objective-C, it goes like this:
int aNumber = arc4Random() % 20;
if (aNumber == 1) {
[theImageView setImage:theImage];
}
How can I do this in Java? I have seen it done this way, but I do not see how I can set the range of numbers (1-20, 2-7, ect).
int aNumber = (int) Math.random()
Docs are your friends
Random rand = new Random();
int n = rand.nextInt(20); // Gives n such that 0 <= n < 20
Documentation:
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
Thus, from this example, we'll have a number between 0 and 19
Math.random() returns an double from [0,1[.
Random.nextInt(int) returns an int from [0, int[.
You can try:
int aNumber = (int) (20 * Math.random()) + 1;
or
Random rand = new Random();
int n = rand.nextInt(20) + 1;
You can use Math.random() to generate a double between 0 and 1 non-inclusive. Android Javadoc here.
I am trying to sum up the digits in a very large number. I have gotten the length of the number with
l = answer.bitLength() but I can't figure out how to increament through each digit using a For loop. Any ideas?
I'm using the java.math.biginteger.
Visual Studio 2005 Version 2.0
I should also add that I can't seem to use <> or any of the simple math options with the biginteger I'm using. If anyone could tell me how to use a different biginteger I would be more than willing to swap.
Dim answer As java.math.BigInteger
Dim sum As Integer = 0
Dim x As Integer
Dim i As Integer
'Sets value of answer equal to 1
answer = java.math.BigInteger.valueOf(1)
'gets 100!
For i = 1 To 100
answer = answer.multiply(java.math.BigInteger.valueOf(i))
Next
'gets length of answer
Dim l As Integer
l = answer.bitLength()
'Sums up digits in 100!
For x = 0 To l - 1
'Need to pull each character here to add them all up
Next
Final Solution for summing up the digits. Thanks to wageoghe.
Dim r As Integer
Dim s As Integer
s = 0
While (answer.compareTo(java.math.BigInteger.valueOf(0)) > 0)
r = answer.mod(java.math.BigInteger.valueOf(10)).ToString()
s = s + r
answer = answer.divide(java.math.BigInteger.valueOf(10))
End While
Something like this should work:
Dim bi As New System.Numerics.BigInteger(12345)
Dim c As Char
Dim s As Long
s = 0
For Each c In bi.ToString()
s = s + Integer.Parse(c.ToString())
Next
Or this more conventional way using Mod and / (integer division)
Dim bi As New System.Numerics.BigInteger(12345)
Dim s As Long
Dim r As Integer
s = 0
While bi <> 0
r = bi Mod 10
s = s + r
bi = bi / 10
End While
If you think of the number as a list of binary characters, then you could get the least significant hex digit by ANDing the number with 0xF. If you then shifted the number right by 4 bits (>> 4), then you could get the next hex digit.
After you get all of the hex digits, you could sum them up and then convert them to decimal.
Another approach, is to do the following (this assumes that answer is positive):
int sum = 0;
while(answer > 0){
sum += answer % 10;
answer /= 10;
}