Not getting the satisfactory output. why? - java

Im new to java.. and after writing a code im getting a solution which was unexpected from my side. Please guide me why my output isnt 5 , 5 ?
I had written a code -
import java.util.*;
public class hwlec3 {
public static void main(String args[]) {
int x = 2;
int y = 5;
int exp1 = (x * y / x);
int exp2 = (x * (y / x));
System.out.print(exp1 + " , ");
System.out.print(exp2);
}
}
I was expecting an output -
5,5
But i got an output -
5,4

Adding onto what the other person said, integer does not account for remainder so (y/x) results in 2 instead of 2.5. The .5 is gone, since the variable is declared as an integer. Thus 2*2 = 4. You could fix this by using double instead of integer.

Related

Why are my cos(x) outputs out of bound 1 and -1?

My task is to implement the cos(x) function withou using Math. library and with the taylor polynom, my code looks like this:
public class Cosinus {
public static void main(String[] args) {
/*if(args.length == 0){
System.out.println("ERROR: Geben Sie ein Argument für x ein!");
return;
}*/
double x = 5;
double summand1 = (x*x) / 2;
double summand2 = (x*x*x*x) / (2*3*4);
double summand3 = (x*x*x*x*x*x) / (2*3*4*5*6);
double summand4 = (x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8);
double summand5 = (x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10);
double summand6 = (x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12);
double summand7 = (x*x*x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12*13*14);
//double summand8 = (x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12*13*14*15*16);
//double summand9 = (x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18);
//double summand10 = (x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18*19*20);
double cosinusFunktion = (((((((1 - summand1) + summand2) - summand3) + summand4) - summand5) + summand6) - summand7);
System.out.println(cosinusFunktion);
}
}
For x = 1, 2, 3, and 4 Y is between 1 and -1
but with x = 5 it goes too -4 and if the x are even getting bigger this continues too 1287918274.
I cant solve this task but tthe task says it is enough to implement this funktion iwth the taylor polynom and the first 11 summand. I tried this too, but then even with x = 1 the bounds are broken. How can i solve this, so x = 42.5 is in bound of -1 and 1?
Tried more summands to make the result more excact, but the bounds get broken even more.
tried implement the periodicity of x-2*PI, but I dont know where to put it and results get messed up eeven more.
you are getting an integer overflow for the factorial in the summand7 line
as a simple fix you can change the line to:
double summand7 = (x*x*x*x*x*x*x*x*x*x*x*x*x*x) / ((double) 2*3*4*5*6*7*8*9*10*11*12*13*14);
The Taylor expansion will always blow up for larger inputs. However, since:
sin(x) = sin(x + n*2*pi) // for any integer n
You can simply pre-process you input with a modulus function to prevent your output from blowing up.
I can't test compile right now, but if memory serves, you would add one of the following lines prior to computing your first summand:
x = x%(Math.PI*2)
Or, if you can't use Math
x = x%((double)3.14159265358979323846*2)

Calculating modulo inverse in java

I was trying to figure out a way to calculate modulo inverse using java so I wrote this function to do it:
public static int privatekey(int primeprod, int e, int lambda)
{
Random random = new Random();
float d = 0;
//extended euler's theorem is
//d = (1 + x*lambda) / e
//d is smaller than primeprod
while(true)
{
int d = random.nextInt(200) + 1;
System.out.println("seed: "+x);
var = (1 + (x*lambda)) / e;
System.out.println("var: "+d);
if(isInteger(d) && d < primeprod)
{
break;
}
}
int finalvar = (int)d;
return finalvar;
}
I felt that it was going wrong so I reversed euclidean theorem extension I used above as follows
1 + x.lambda
------------- = d (this one is the equation to find out d when x is any integer)
e
de = 1 + x.lambda
de - 1 = x.lambda
de - 1
------- = x (this one is to check whether the value obtained by the above equation is true or not by checking if x is the same value we had chosen for our calculation in the first place)
lambda
After doing this check I found that the value of x I obtained in the reversed equation I had solved to check for mistakes is not equal but approximate to the original random value which I had generated.
For example taking these values:
e = 327
lambda = 484
x = 76
We get d as 112.0
later We reverse The equation to find the value of x to confirm
we get:
x = 75.667355372 (Which is approximate to the original value)
I wasn't able to figure out where it was going wrong.
To look at the full program please visit this link.
Please tell me If I have done something wrong here.
Thank You in advance!
Alright I got an answer to this problem.
The Issue was I was performing arithmetic operations on integer so the value I got as result was an integer.
Instead of using integer I later used Double to do the same operation and I resolved the issue.
public static int privatekey(Double primeprod, Double e, Double lambda)
{
Random random = new Random();
float d = 0;
//extended euler's theorem is
//d = (1 + x*lambda) / e
//d is smaller than primeprod
while(true)
{
int d = random.nextInt(200) + 1;
System.out.println("seed: "+x);
var = (1 + (x*lambda)) / e;
System.out.println("var: "+d);
if(isInteger(d) && d < primeprod)
{
break;
}
}
int finalvar = (int)d;
return finalvar;
}
This resolved the issue.

My simple Java pi calculator always seems to give infinity? [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I am coding this simple pi calculator for my Java class as a part of us learning about basic loops and it seems like everything is OK except the values printed for pi is infinity when it should be 3.14...something according to the number of iterations. I read that this could be maybe related to a double variable dividing by 0 and it's giving a weird infinity output instead of a normal Java runtime exception?
Here's my code:
package lab05;
public class Lab05 {
public static void main(String[] args) {
// Variable declarations
double pie = 3;
double savepie = 0;
double term = 0;
double savei = 0;
double sign = 1;
boolean isRangeFound = false;
int i;
// For loop
for (i=0; i <= 1000;) { // Only up to 1000 iterations before loop must end.
term = (sign * 4) / ((2*i) * (2*i+1) * (2*i+2));
pie = pie + term;
sign = (-1 * sign);
if (isRangeFound==false && (pie >=3.14159265 & pie < 3.14159266)) {
savepie = pie;
savei = i;
isRangeFound = true;
}
if (i == 200||i == 500||i == 1000) {
System.out.print("The value of \u03C0 is: ");
System.out.printf("%.10f",pie);
System.out.print(" when i = " + i);
System.out.println(" ");
}
i++;
}
// Final output statement
System.out.println ("The number of iterations to get to 3.14159265 is " + savei + ".");
System.out.printf("\n\u03C0 = %.10f",savepie);
System.out.println(" ");
}
}
Here's my output in Netbeans:
The value of π is: Infinity when i = 200
The value of π is: Infinity when i = 500
The value of π is: Infinity when i = 1000
The number of iterations to get to 3.14159265 is 0.0.
π = 0.0000000000
BUILD SUCCESSFUL (total time: 0 seconds)
Here's the link to the instructions that I should follow with a Visual Logic flowchart that I tried to follow to the T. Thanks.
https://www.dropbox.com/s/2m26a32afedk9yu/Lab05%20Assignment%281%29.pdf?dl=0
You need to start your loop when i=1? The way you have it, when i=0, then term will be infinity (due to the divide-by-zero), and so pie will be infinity as well.

Head First Java Puzzle4 (Chapter 4, pg 91) Explanation

Below is the solution to, and output of,the subject puzzle, and I'm having trouble understanding how it works.
public class Puzzle4 {
public static void main(String[] args) {
Puzzle4b[] obs = new Puzzle4b[6];
int y = 1;
int x = 0;
int result = 0;
while (x<6) {
obs[x] = new Puzzle4b();
obs[x].ivar = y;
y = y*10;
x = x+1;
}
x = 6;
while (x>0) {
x = x-1;
result = result + obs[x].doStuff(x);
}
System.out.println("result " + result);
}
}
class Puzzle4b {
int ivar;
public int doStuff(int factor) {
if (ivar>100) {
return ivar*factor;
} else {
return ivar*(5-factor);
}
}
}
Output:
result 543345
From my understanding, the first While loop will run through 6 times (from x==0 to x==5). The y variable, and in turn 'ivar', will have a value of 1,000,000 (I think this is where I'm going wrong, but I'll continue in hopes of being corrected).
The second While loop is a bit confusing to me. It'll run through 6 times, with the second line of the loop passing the 'x' values to the doStuff method for it to return a value. The numbers I'm coming up with for the result don't match the actual result.
Any help here would be appreciated. Please let me know if I'm thinking about it the wrong way. If someone wants to reformat my code to align more closely with industry standards, it would be great to learn good habits from the start!
this piece of code `
obs[x].ivar = y;
y = y*10;
will cause first ivar = y = 1 then multiple y
so it'll be {1 - 10 - 100 - 1,000 - 10,000 - 100,000}
the second loop x will be { 5 , 4 , 3 , 2 , 1 , 0 }
so it'll start like this result = result+obs[5].doStuff[5];
i guess all the misunderstanding that x in element 1 will equal y in element 5
and x in element 2 will equal y in element 4 and so on " because x is incrementing and y is decrementing
so it will go like this
(ivar > 100 )
ivar * (5-factor)
x[3] * y[2] = 1000 * (5-2) = 3000
x[4] * y[1] = 10000 * (5-1) = 40000
x[5] * y [0] = 100000 * (5-0) = 500000
then (ivar < 100)
ivar * factor
x[1] * y [5] = 1 * 5 = 5
x[2] * y [4] = 10 * 4 = 40
x[3] * y [3] = 100 * 3= 300
then if you add all the numbers together you'll have your output
In the second while loop,
while(x>0) will give 543340
Instead While (x>=0) should give the required output
If I'm not wrong
For me an easy way to break this down is stepping through and seeing exactly where the values are coming from. I've done this below and commented it into the code.
public class Puzzle4 {
public static void main(String[] args) {
Puzzle4b[] obs = new Puzzle4b[6];
int y = 1;
int x = 0;
int result = 0;
// let's break out of the loops
obs[0] = new Puzzle4b();
obs[0].ivar = 1;
obs[1] = new Puzzle4b();
obs[1].ivar = 10;
obs[2] = new Puzzle4b();
obs[2].ivar = 100;
obs[3] = new Puzzle4b();
obs[3].ivar = 1000;
obs[4] = new Puzzle4b();
obs[4].ivar = 10000;
obs[5] = new Puzzle4b();
obs[5].ivar = 100000;
// ivar's = 1, 10, 100, 1000, 10000, 100000
result = result + obs[5].doStuff(5); // 0 + (5 * 100000)
result = result + obs[4].doStuff(4); // 500000 + (4 * 10000)
result = result + obs[3].doStuff(3); // 540000 + (3 * 1000)
result = result + obs[2].doStuff(2); // 543000 + ((5 - 2) * 100)
result = result + obs[1].doStuff(1); // 543300 + ((5-1) * 10)
result = result + obs[0].doStuff(0); // 543340 + ((5-0) * 1)
// result = 543345
}
System.out.println("result " + result);
}
}
class Puzzle4b {
int ivar;
public int doStuff(int factor) {
if (ivar>100) {
return ivar*factor;
} else {
return ivar*(5-factor);
}
}
}
Hope this has helped you understand the example.
The key is to understand what each loop does.
1st one is nothing but just assigning values to ivar variable of each array object. You do it with "x" value as index.
2nd one you still get indices from what "x" variable currently is. And then you need to remember what ivar value is for exactly this index. With that in mind you will be able to understand what condition of doStuff method is true and what expression you should use respectively.
Also, you have to remember of what value "result" variable get on each loop iteration. Like 1st iteration result = 500 000. then 2nd one will be result = 500 000 + doStuff.
And last but not least, not without reason the book calls you to do exercises on paper. It leads to a lot of writing but also to understanding what code does on each and every line.

Starting to learn Java 'Int' and 'Double' [duplicate]

This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 6 years ago.
When dividing two 'int' variables and saving the result into a 'double' variable, anything to the right of the decimal point is just zero?
See the three examples below.
Thank you in advance, Mike
Example 1
public class MyClass {
public static void main(String[] args) {
int x, y, answer;
x = 70;
y = 30;
answer = x / y;
System.out.print(answer);
}
}
Output = 2 (I understand the result, all variables defined as 'int')
Example 2
public class MyClass {
public static void main(String[] args) {
int x, y;
double answer;
x = 70;
y = 30;
answer = x / y;
System.out.print(answer);
}
}
Output = 2.0 (I don't understand the result, the variable answer is 'double' and I expected 2.3333333333333335)
Example 3
public class MyClass {
public static void main(String[] args) {
double x, y, answer;
x = 70;
y = 30;
answer = x / y;
System.out.print(answer);
}
}
Output = 2.3333333333333335 (I understand the result, all variables defined as 'double')
Let's get a closer look at how Java executes this line in the second piece of code:
answer = x / y;
First, Java sees a = operator so it knows that this is an assignment statement. To evaluate an assignment, evaluate the expression on the rignt then put the result into the variable on the left. Therefore, it evaluates the right hand side first.
x / y
Hmm... what could be the result of that? x is an int and y is an int and you have a / operator. I know the division operator can be applied to two int operands, so let me get the value of x and y. Ah! It's 70 / 30! Since it is an integer divided by an integer, the result must be an integer! The result is 2!
Now the assignment becomes:
answer = 2;
Java finds an integer on the right and a double variable on the left, so it converts 2 into a double and puts it in the variable.
Dividing two integers will yield an integer (which is 2 in this case). It just so happens that you chose to store this integer in a double, so it is now represented as 2.0.
The first code reads everything as int and gives an int. The second code reads two ints and gives the double of the ints (example: 10/5 = 2, but 2 in double is 2.0). In the end the third code reads everything as double so for example 70/30 (read as 70.0/30.0) = 2.33...
The Example 2, when compute answer = x / y, the first compute x / y and result is 2 then convert the double type 2.0.

Categories

Resources