I am using the following code, it generates numbers randomly but the problem is, I am not able to figure out why does not it generate the number 1
int ran, g, d, col, ran2;
double y = 1000 * (Double.parseDouble(t2.getText()));
int x = (int) y;
d = Integer.parseInt(anum.getText());
double c = 10;
int prevrandom = Integer.parseInt(lnum.getText());
lnum.setText("");
lnum.setVisible(true);
for (g = 0; g==0;) {
d = Integer.parseInt(anum.getText());
ran = (int) (Math.random() * (c)); // Random Number Creation Starts
if (ran > (c / 10)) {
g = 1;
ran2 = ((int) (Math.random() * 10)) % 2;
if (ran2 == 1) {
ran = ran * (-1);
}
d = d + ran;
if (d < 0) {
ran = ran * (-1);
d = d + (2 * ran);
}
int a = d - ran;
if(prevrandom==ran){
g=0;
}
if(g==1){
lnum.setText("" + ran);
}
}
}
I call this function(button) from somewhere. The problem comes when the sum ('a') becomes 4, according to my conditions it shouldn't allow any number other than 'one' and thus it goes into infinite loop.
I am talking about ran variable. Which I get after multiplying Math.random with 10^x where x is a positive integer.
Here ran2 is a number with value 1 or 0. As I multiply Math.Random with 10 which gives a 1 digit number and I mod it with 2.
THis is a 14 year old boy new to java. it would be greatful of people out here to help rather than discourage.
Look at the Javadoc:
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.
If you need integer random numbers, you might be better off with java.util.Random. To generate a random integer in the range a..b (inclusively), you can use
Random random=new Random();
int rnd=a+random.nextInt(b-a+1);
The problem lies in the code
if (ran > (c / 10)) {
The random number gets created which is even equal to one; but here due to the sign '>' it gets rejected.
Use '>=' instead.
ran = (int) (Math.random() * (c)); where c is from 10 to 10^x
This can be 1 as follows.
int c = 1000;
for (int i = 0; i < 1000; i++) {
int count = 0;
int ran;
do {
ran = (int) (Math.random() * (c)); // where c is from 10 to 10^x
count++;
} while (ran != 1);
System.out.println("count: " + count);
}
prints sometime like
count: 1756
count: 86
count: 839
count: 542
count: 365
....
count: 37
count: 2100
count: 825
count: 728
count: 1444
count: 1943
It returns 1 a thousand time in less than a second.
Related
I need to generate random numbers using Math.random() between two given values but ignoring on this comparation the two given values or just one depending the case.
Those are the values to do:
Between -7 and 0, excluding 0.
Between 0 and 4, both of the values excluded.
Between 4 and 5, excluding 4.
I've tried with the first case the following code:
double fv = (-7) + Math.random() * (0 -7);
System.out.println(fv);
But it's giving me weird resoults like -13.00123.
It's for a degree excercise so I have to keep it simple.
Any ideas?
The correct formula for random numbers in a range is Min + (Math.random() * (Max - Min)) (including lower bound and excluding upper bound).
For your numbers the correct way would be
double fv = (-7) + Math.random() * (0 - -7);
Since you used only one - in the formula the Minvalue was assumed to be 7 and not -7 which leads to wrong results.
double fv = (-7) + Math.random() * 7;
System.out.println(fv);
creates a random double between (and including) 0.0 and 1.0 (excluding the 1.0 itself). Multiplying by 7 makes a hypothetical range of 0 to 6.99[...]9. Subtracting by 7 makes a the range of the random number from -7 to 0.00[...]01
You can use this information to deduct the formulas for your desired random numbers in a similar way.
Try this
Random random = new Random();
random.ints(1, -7, 0).forEach(System.out::println);
Last value in ints() method will be excluded.
You can set-up an enum to determine inclusivity.
import java.util.concurrent.ThreadLocalRandom;
public class RandomUtil {
private enum Inclusivity { INCLUSIVE, EXCLUSIVE; }
public static double randomDouble(double minValue, double maxValue) {
return randomDouble(minValue, maxValue, Inclusivity.INCLUSIVE, Inclusivity.EXCLUSIVE);
}
public static double randomDouble(double minValue, double maxValue, Inclusivity minInclusivity, Inclusivity maxInclusivity) {
if (minInclusivity == Inclusivity.EXCLUSIVE) {
minValue += 1;
}
if (maxInclusivity == Inclusivity.INCLUSIVE) {
maxValue += 1;
}
return ThreadLocalRandom.current().nextDouble(minValue, maxValue);
}
public static void main(String[] args) {
System.out.println(randomDouble(-7, 0, Inclusivity.INCLUSIVE, Inclusivity.EXCLUSIVE)); // default
System.out.println(randomDouble( 0, 4, Inclusivity.EXCLUSIVE, Inclusivity.EXCLUSIVE));
System.out.println(randomDouble( 4, 5, Inclusivity.EXCLUSIVE, Inclusivity.INCLUSIVE));
}
}
Generate a number between -7 and 0 excluding 0.
double w = (Math.random() - 1) * 7;
When the random number = 0, the required value will be -7. But the required value but will never be 0 since Math.random() will never be 1.
For the others
// between 0 and 4 both values excluded.
double r = Math.random();
double x = (-3 * r); // -3 < x <= 0
double xx = r + 3; // 3 <= xx < 4
x += xx; // 0 < x < 4
// between 4 and 5 excluding 4
double w = (-1 * Math.random()); // -1 < w <= 0
w += 5; // 4 < w <= 5
package test;
import java.util.Scanner;
public class SplitNumber
{
public static void main(String[] args)
{
int num, temp, factor = 1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
num = sc.nextInt();
temp = num;
while (temp != 0) {
temp = temp / 10;
factor = factor * 10;
}
System.out.print("Each digits of given number are: ");
while (factor > 1) {
factor = factor / 10;
System.out.print((num / factor) + " ");
num = num % factor;
}
}
}
I can't understand this int factor's job. Can someone help me to understand this codes algorithm?
In programming languages, if you hold double value in the int,it rounds the number to lower one thus if you do 15/10 it will return 1 as int and if you do 5/10 it will return 0. With this knowledge you can understand.
For example,let the number be 953,
while (temp != 0) {
temp = temp / 10;
factor = factor * 10;
}
1.Iteration temp = 95 , factor = 10
2.Iteration temp = 9 , factor = 100
3.Iteration temp = 0 , factor = 1000
end of while loop because temp is 0.
while (factor > 1) {
factor = factor / 10;
System.out.print((num / factor) + " ");
num = num % factor;
}
1.Iteration num = 953 factor = 100 , 953/100 = 9 (you get first digit)
2.Iteration num = 953%100 = 53 , factor = 10 , 53/10 = 5 (you get second digit)
3.Iteration num = 53%10 = 3 , factor = 1 , 3/1 = 3 (you get last digit)
End of while loop.
Actually it is basic math. When you want to extract nth digit of number, you just have to divide it by 10^n.
The modulus operator to extract the rightmost digit or digits from a number. For example, x % 10 yields the rightmost digit of x (in base 10). Similarly x % 100 yields the last two digits.
Here more info
If you would not care about flipping the order of digits, you could simply write
int num = sc.nextInt();
do {
System.out.println(num % 10);
num = num / 10;
} while(num != 0);
The modulo operation num % 10 calculates the remainder of dividing num by 10, effectively gets the digit at the lowest position ("ones"). 0 % 10 is 0 ... 9 % 10 is 9, 10 % 10 is 0 again, and so on. Then the division by 10 makes the old "tens" the new "ones", and the entire thing is repeated until 0 remains.
The hassle in your code is about emitting the digits in the "correct" order, highest position first, ones last. So it first checks how many digits are in your number, factor grows to the same size in the process. temp=temp/10; has the same role as num=num/10; in the short snippet (cutting a digit from the number in each iteration), and factor=factor*10 "adds" a digit to factor at the same time. [I just stop here as there is an accepted answer already explaining this]
the question is to find the sum of this series
series
i used this code to solve it , but im not quite sure the logic is correct.
the noofterms is how many terms are going to be added
and x is the number that will be assigned to the variable.
does the logic seem correct?
public static double sumOfSeries(double x, int noofterms){
double evennumbers=1;
double oddnumbers=1;
double result=1;
// since the power of x starts from 1 , we start i from 1 and increment by 2
for (int i=1; i<noofterms; i+=2 ){
// we reset starting numbers so we start from them everytime
evennumbers = 1;
oddnumbers = 1;
// everytime the number increases by 2 when it is smaller than i+1
// ex when its equal to 2 , j = 3 , j+1 = 4 so it increments by 2
// when its 4 , j = 5 , j+ 1 = 6 , it increments
for (int j=2; j<=i+1; j+=2){
// multiply by increments of 2
evennumbers= evennumbers * j;
}
// it starts from 1 and increments by 2 so it goes like 1,3,5
for (int z=1; z<=i; z+=2){
oddnumbers = oddnumbers * z;
}
result*=((Math.pow(x, (double)i)) / (double)i) + (oddnumbers/evennumbers);
}
return result;
}
You can do it better. Note that numerators and denominators form two sequences, so you can keep previous terms to efficiently make computations, this will look like this :
long even = 1;
long odd = 1;
double result = x;
for(long i = 1; i < noofterms; i++)
{
even *= 2 * i;
odd *= 2 * i - 1;
double oper = Math.pow(x, (double)(2 * i + 1)) / (double)(2 * i + 1);
result += (double)even / (double)odd * oper;
}
You can improve by using logarithms because even and odd will grow very fast and will lead to overflows :
double even = 0.0;
double odd = 0.0;
double result = x;
double logx = Math.log(x);
for(long i = 1; i < noofterms; i++)
{
even += Math.log((double)(2 * i));
odd += Math.log((double)(2 * i - 1));
double oper = logx * (2 * i + 1) - Math.log((double)(2 * i + 1));
result += Math.exp(even - odd + oper);
}
EDIT: only one sequence could also be computed : p *= (double)(2*i)/(2*i-1). Then the log trick is not useful.
I am trying out a code that finds out whether a number entered is Armstrong or not. Here is the Code:
import java.util.*;
public class Arm {
int a, b, c;
void m1() {
Scanner obj = new Scanner(System.in);
System.out.println("Enter a number");
int number = obj.nextInt();
number = (100 * a) + (10 * b) + (1 * c);
if ((a * a * a) + (b * b * b) + (c * c * c) == number) {
System.out.println("number is armstrong");
} else {
System.out.println("number is not armstrong");
}
}
public static void main(String args[]) {
Arm obj = new Arm();
obj.m1();
}
}
Here the value of a,b and c comes out to be zero. But that is not the correct result. Say if we enter a number 345. Then a,b and c should be 3, 4 and 5 respectively.
Please guide.
That is not how you calculate a, b, c.
To find a,b,c we repeatedly divide by 10 and get the remainder by modulus.
int digit = 0;
int sum = 0;
while(num > 0)
{
digit = num % 10;
sum += Math.pow(digit, 3);
num = num/10;
}
Why do we use / and %
Consider 345.
Now to get the last digit what can be done?
What does a modulus return? The remainder, so If we perform %10 we get the last digit.
345 % 10 = 5
Now we want the second last digit.
So we divide the number by 10, so we get the quotient
345 / 10 = 34
Now again if we can perform the modulus we get the 4 and so on..
What does 100 * a + 10 * b + 1 * c do?
That is used to get a number if we have the individual digits.
Suppose we have 3, 4, 5 we know that we get 345 out of it but how do we do it?
3 * 100 = 300
4 * 10 = 40
5 * 1 = 5
-----------
300 + 40 + 5 = 345
Now to complete your whole program.
public boolean isAmg(int num)
{
int digit = 0;
int sum = 0;
int copyNum = num; //used to check at the last
while(num > 0)
{
digit = num % 10;
sum += Math.pow(digit, 3);
num = num / 10;
}
return sum == copyNum;
}
I just solve this but want know more efficient way to do matrix multiplication
M = | 1 0 3 |
| 1 0 2 |
| 0 5 0 |
f[n] = M^n
I have implemented using Exponentiation_by_squaring
Is there more efficient then this ?
I guess, this is actually more suitable for math as there's a closed form solution. It's system of Linear homogeneous recurrence relations with constant coefficients.
Another posibility: You could speed up the program twice by deriving a formula for two steps, i.e., express RR(i) etc. via RR(i-2), etc.
And this can be repeated, so you can jump much faster.
One problem is that your calculations are overflowing. If you run it for K=1 and J=9, you get -334328541#510576792#-817751931.
The easiest fix for that is to do % 1000000006 in calculateProduction.
About efficiency, I would look at this problem as performing matrix multiplications.
You start with the vector (i.e. 1*3 matrix):
3 1 0
And at each step you multiply it (mod 1000000006) with the matrix:
1 1 0
0 0 5
3 2 0
Let's call the vector V and the matrix M. Basically you need to calculate V*MN. Since matrix multiplication is associative, you can calculate MN first, and do that recursively:
MN = (MN/2)2 if N is even, or
MN = M*(M[N/2])2 if N is odd
You don't need to calculate MM. This is why:
PP[i] = 5*MM[i-1] = 5*(RR[i-2] + 2*PP[i-2])
RR[i] = RR[i-1] + 3*PP[i-1] = (RR[i-2] + 3*PP[i-2]) + 3*PP[i-1]
See? You don't need to calculate MM at each step. This should be the algorithm:
public class RecurrenceMachine {
private static final int max = 1000000006;
public String calculate(int k, int j) {
long n = k * j;
if (n < 1)
return "error";
long RRi2 = 3;
long PPi2 = 0;
long RRi1 = 3 + 3 * PPi2;
long PPi1 = 5 * 1;
if (n == 1)
return RRi1 + "##" + (RRi2 + 2 * PPi2) + "##" + PPi1;
Long PPi = (long) 0, RRi = (long) 0, temp;
int i;
for (i = 2; i <= n; i++) {
temp = RRi2 + 2 * PPi2;
PPi = 5 * temp;
if (PPi >= max)
PPi %= max;
RRi = temp + PPi2 + 3 * PPi1;
if (RRi >= max)
RRi %= max;
RRi2 = RRi1;
PPi2 = PPi1;
RRi1 = RRi;
PPi1 = PPi;
}
return RRi + "##" + (RRi2 + 2 * PPi2) % max + "##" + PPi1;
}
}
I tried only with small values and it seems to work.