This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Im working on a program I need to finish tonight, and basically it does a cheep version of factoring...
The problem is, that its not giving me numbers, but NaN.
Heres my code:
Class 1(Part that deals with this program):
System.out.println("--------------------------------------------------");
System.out.println(" ~Factoring~");
System.out.println("--------------------------------------------------");
System.out.println("in a polynomial, there are 3 important numbers used");
System.out.println("to figure out x. they are a, b, and c, shown below.\n");
System.out.println("\t\t1x^2 +2x -3");
System.out.println("\t\t^ ^ ^");
System.out.println("\t\ta b c");
System.out.print("\nPlease type a, b, and c here[a b c]: ");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
mathey factor = new mathey(a,b,c, chooser);
System.out.print(factor.solvefact());
Class 2:
public class mathey
{
double a,b,c;
double solution1;
double solution2;
double discriminant;
double x1 = 0;
double x2 = 0;
public mathey(int aN, int bN, int cN)
{
a = aN;
b = bN;
c = cN;
discriminant = (b*b)-4*a*c;
solvea();
solveb();
}
public String solvea()
{
solution1 = (-1*b + Math.sqrt(discriminant))/(2*a);
x1 = solution1;
if(discriminant > 0)
{
return"x = " + solution1;
}
else if(discriminant == 0)
{
return "x = " + solution1;
}
else
{
double root1complex = -b/(2*a);
double root1complex2 = Math.sqrt(-discriminant)/(2*a);
return root1complex + " + " + root1complex2 + " i ";
}
}
public String solveb()
{
solution2 = (-1*b - Math.sqrt(discriminant))/(2*a);
x2 = solution2;
if(discriminant > 0)
{
return"x = " + solution2;
}
else if(discriminant == 0)
{
return"x = " + solution2;
}
else
{
double root1complex = -b/(2*a);
double root1complex2 = Math.sqrt(-discriminant)/(2*a);
return root1complex + " - " + root1complex2 + " i ";
}
}
public mathey(int aFact, int bFact ,int cFact, int chooser)
{
a = aFact; b = bFact; c = cFact;
discriminant = (b*b)-4*a*c;
solvea();
solveb();
solvefact();
}
public String solvefact()
{
String Answer = "";
if((int)solution1 == solution1)
{
int wholeNum = (int)solution1/1;
double numerator = (solution1%1) * 10;
int denominator = 10;
while(numerator > denominator) {
denominator = denominator * 10;
}
Answer+="("+denominator+"x + "+((denominator * wholeNum) + numerator)+")";
}
else
{
Answer +="( x + " +(solution1*-1) +")";
}
if((int)solution2 == solution2)
{
int wholeNum = (int)solution2/1;
double numerator = (solution2%1) * 10;
int denominator = 10;
while(numerator > denominator) {
denominator = denominator * 10;
}
Answer+="("+denominator+"x + "+((denominator * wholeNum) + numerator)+")";
}
else
{
Answer +="( x + " +(solution2*-1) +")";
}
return Answer;
}
Heres the output:
Choose a Way to Solve
1. Quadratic Formula
2. Factoring
Which Method? [1/2]: 2
--------------------------------------------------
~Factoring~
--------------------------------------------------
in a polynomial, there are 3 important numbers used
to figure out x. they are a, b, and c, shown below.
1x^2 +2x -3
^ ^ ^
a b c
Please type a, b, and c here[a b c]: 1 2 -3
(10x + 10.0)(10x + -30.0)
How Do I fix this, so I get the Output I should get? (x + 3.0)(x-1.0)
In your 4-param constructor Mathey() (which is the constructor you are calling) you are redeclaring the variables a, b, c and assigning the values passed in to them, masking the instance variables which remain equal to 0 (the default). These local variables are only in scope in the constructor. In solveA() and solveB(), a, b, c again refer to the instance variables (which are all 0), so you're dividing by 2*a = 0, which makes solution1 and solution2 equal to NaN.
Change the line in the second constructor (if you continue to use it) from
double a = aN, b = bN, c = cN;
to
a = aN, b = bN, c = cN;
to solve the masking issue. You most likely want the instance variables to be doubles rather than ints, though, so change
int a;int b;int c;
to
double a, b, c;
(you can do multiple declarations of the same type like this).
I don't know why you have two Mathey constructors, so either scrap the second one (what is chooser?) and just use the first, or make sure the second one also assigns a value to determinant.
This should be a start, anyway.
You should check if you have the possibility your code by unit testing the functions.
For instance I noticed you used a {%} operator with a double number. That operator works with integers, and may drag the NaN result until the end.
You are also declaring variables in mathey() and then trying to use them in solvea() solveb() where they don't exist.
Related
i have a question that goes with:
In Java, if we divide two integers, the result is another integer, but the result might not be correct. For example, 4/2 = 2, but 5/2 = 2.5 but in Java the result would be 2 when both 5 and 2 values are stored as integer values. The program should check if the numbers the result of the division is the same when the values are both integers and when they are floats.
So that I spend over 1 hour to figure this q but i have a problem with the ending part. What it meant in this part: "The program should check if the numbers the result of the division is the same when the values are both integers and when they are floats."
import java.util.Scanner;
class StartUp2{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please type the first number that you want be devided: ");
int a = sc.nextInt();
float b = a;
System.out.println("Please type another number that you want to devide with:");
int c = sc.nextInt();
float d = c;
}
}
Do the division once with variables declared as int and once with float. Then compare the results.
int a = 42;
int b = 5;
float result = a/b;
float a = 42.0f;
float b = 5.0f;
float result = a/b;
Or as a self-contained function:
void compareDivision(final int a, final int b) {
float intResult = a/b;
float floatResult = (float)a/(float)b; // cast to float
if (intResult != floatResult) {
System.out.println("Results are different: " + intResult + " != " + floatResult);
}
}
Building on the code from your updated question:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please type the first number that you want be divided: ");
int a = sc.nextInt();
float b = a;
System.out.println("Please type another number that you want to divide with:");
int c = sc.nextInt();
float d = c;
float intResult = a/c;
float floatResult = b/d;
if (intResult != floatResult) {
System.out.println("Results are different: " + intResult + " != " + floatResult);
}
}
If you were to divide integers 5/2, then you would end up with 2.
Reverse the operation, multiply the result by the divisor, 2 * 2, and you end up with 4. Therefore your program should return false since it didn't equal the dividend, 5.
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.
This question already has an answer here:
Java Division error
(1 answer)
Closed 7 years ago.
I was trying to create a probability calculator for fun, but for some reason, java gets the incorrect answer when I divide two numbers. Here is my code....
import javax.swing.JOptionPane;
public class ProbabilityCalculator {
public static void main(String args[]) {
String a = JOptionPane.showInputDialog("One out of.....");
int x = Integer.parseInt(a);
int numLoops = 1000;
int y = 0;
int n = 0;
for (int i = 0; i < numLoops; i++) {
int result = (int) (Math.random() * x + 1);
int result2 = (int) (Math.random() * x + 1);
if (result == result2)
y++;
else
n++;
}
System.out.println(y);
System.out.println(numLoops);
System.out.println(y/numLoops);
double d = (y/numLoops) * 100; //get it? double d??
JOptionPane.showMessageDialog(null, "Out of " + numLoops + " trials, "
+ y + " times it worked, while " + n + " times it didn't.");
JOptionPane.showMessageDialog(null, "Your percentage was " + d
+ "%.");
System.exit(0);
}
}
When I ran this code one time, y was 514, numLoops was 1000, but d would be 0, when d is supposed to be 51.4 (514 / 1000 * 100). Why is this happening?
y/numLoops will be an integer since both arguments are ints. Try (double)y/numLoops or y/(double)numLoops instead.
If you decompose double d = (y/numLoops) * 100; you'll get something similar to those steps:
int r = y/numLoops; - according to the spec an operation having two integer operands will have an int result.
double d = r * 100 here r will be 0 due to being int.
I saw someone else posted this problem but didn't word it properly so he didn't end up receiving any help, so I figured I would try and be more direct.
Here is the problem proposed to us :
// Write and submit your code in a file called Intersect.java. Use the IO module to read inputs. Use System.out.println() to print your answer.
Write a program that calculates the intersection between 2 equations:
a degree-2 (quadratic) polynomial i.e.
y = dx^2 + fx + g
where d, f, and g are constants
and a degree-1 (linear) equation i.e.
y = mx + b
where m is the slope and b is a constant
The above is just text, not code that could appear in a Java program.
Ask the user for the constant values in each equation. Output the intersection(s) as ordered pair(s) (x,y), or "none" if none exists. Below is an example run.
java Intersect
Enter the constant d:
5
Enter the constant f:
-3
Enter the constant g:
2
Enter the constant m:
1
Enter the constant b:
3
The intersection(s) is/are:
(1,4)
(-0.20,2.8)
//
The main problem is essentially asking us to write a code that asks the user to imput the individual constants and the slope of the two equations, one being a quadratic polynomial and the other being a linear equation in point-slope.
I understand that we have to use the quadratic equation in the code, however I have no idea how to actually code this in.
Once we have had the user imput the constants, in this case 5 (d,f,g,m,b; with m being slope) we need to have the code run the calculations to imput those constants into the above example ( y = dx^2 + fx + g | y = mx + b) and return either "none" if there is no intersection, or if it does intersect, the ordered pair at which it does intersect (x,y).
I know already that if 0 is entered as the constants it returns (NaN,NaN) which I also know needs to be re-written to None.
so far I only have the following:
public class Intersect {
public static void main(String[] args) {
System.out.println("Enter the constant d:");
int d = IO.readInt();
System.out.println("Enter the constant f:");
int f = IO.readInt();
System.out.println("Enter the constant g:");
int g = IO.readInt();
System.out.println("Enter the constant m:");
int m = IO.readInt();
System.out.println("Enter the constant b:");
int b = IO.readInt();
If anyone can shed some light on this that would be fantastic, thanks!
EDIT1 :
So far i've changed the code to the following, however, I still don't know how to get it to return to me an answer:
public class Intersect {
public static void main(String[] args) {
System.out.println("Enter the constant d:");
int d = IO.readInt();
System.out.println("Enter the constant f:");
int f = IO.readInt();
System.out.println("Enter the constant g:");
int g = IO.readInt();
System.out.println("Enter the constant m:");
int m = IO.readInt();
System.out.println("Enter the constant b:");
int b = IO.readInt();
//y = dx^2 + fx + g
//y = mx + b
//mx + b = dx^2 + fx + g
//x^2 * (d) + x * ( f - m ) + ( g - b )
int A = d;
int B = f - m;
int C = g - b;
double x1 = - B + Math.sqrt( B^2 - 4 * A * C ) / (2 * A);
double x2 = - B - Math.sqrt( B^2 - 4 * A * C ) / (2 * A);
double y1 = m * x1 + b;
double y2 = m * x1 + b;
}
Also, eclipse is telling me that x2,y1, and y2 aren't used at all.
I know I need to use System.out.println() however I don't understand what I can put there to make the answer an ordered pair. Also, I tried setting an If statement to have the answer return None instead of NaN however it instead returns, NaN None.
There are a lot of special cases you have to take into account.
I hope I've got them all right.
So after the initialization of the values you can put this:
// calculating some useful values.
double t = -(f - m) / (2.0 * d);
double u = t * t - (g - b) / (double) d;
// the first polynomial is linear, so both terms are.
if (d == 0) {
// both linear functions have the same slope.
if (f == m) {
// both functions are shifted the same amount along the y-Axis.
if (g == b)
// the functions lie on top of each other.
System.out.println("There is an infinite amount intersections");
// the functions are shifted different amounts along the y-Axis.
else
// the lines are parallel.
System.out.println("There are no intersections");
}
// both linear functions have different slopes.
else {
// solve linear equation.
double x = (b - g) / (double) (f - m);
double y = m * x + b;
System.out.println("The intersection is: (" + x + "," + y + ")");
}
}
// the functions do not cross each other.
else if (u < 0)
System.out.println("There are no intersections");
// the linear function is a tangent to the quadratic function.
else if (u == 0) {
// solve equation.
double x = t;
double y = m * x + b;
System.out.println("The intersection is: (" + x + "," + y + ")");
}
// the linear function intersects the quadratic function at two points.
else {
// solve quadratic equation.
double x1 = t + Math.sqrt(u);
double x2 = t - Math.sqrt(u);
double y1 = m * x1 + b;
double y2 = m * x2 + b;
System.out.println("The intersections are: (" + x1 + "," + y1 + ") (" + x2 + "," + y2 + ")");
}
i guess....
//y = dx^2 + fx + g
//y = mx + b
//mx + b = dx^2 + fx + g
//x^2 * (d) + x * ( f - m ) + ( g - b )
A = d
B = f - m
C = g - b
x1 = - B + sqr( B^2 - 4 * A * C ) / (2 * A)
x2 = - B - sqr( B^2 - 4 * A * C ) / (2 * A)
y1 = m * x1 + b
y2 = m * x1 + b
Please help. I've been working on this non stop and can't get it right. The issue I'm having is that the output I'm getting for the inverse is always 1.
This is the code that I have (it computes GCD and trying to modify so it also computes a^-1):
import java.util.Scanner;
public class scratchwork
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
long n, a, on, oa;
long gcd = 0;
System.out.println("Please enter your dividend:");
n= keyboard.nextLong();
System.out.println("Please enter your divisor:");
a= keyboard.nextLong();
on= n;
oa= a;
while (a!= 0)
{gcd=a;
a= n% a;
n= gcd;
}
System.out.println("Results: GCD(" + odd + ", " + odr + ") = " + gcd);
long vX; vS; vT; vY; q; vR; vZ; m; b;
vX = n; vY=a;
vS = 0; vT = 1; m=0; b=0;
while (a != 0)
{
m=vT;;
b=vX;
q = n / a;
vR = vS - q*vT;
tZ = n - q*a;
vS = vT; n = da;
vT = tY; dY = vZ;
}
if (d>1) System.out.println("Inverse does not exist.");
else System.out.println("The inverse of "+oa+" mod "+on+" is "+vT);
}
}
The code you've posted does not declare most of the variables it uses and thus dues not compile. Most importantly, the variable v it uses to output the result is neither defined nor assigned to anywhere in the posted code - whatever it contains has nothing to do with the calculation.
Can we see the variables declaration? If you mix integer with double, your numbers can be rounded. Anyway, if you only want the inverse, juste use Math.pow(a, -1);
Also, in the second loop, you never set "a" so it will loop forever:
while (a != 0)
{
m=vT;;
b=vX;
q = n / a;
vR = vS - q*vT;
tZ = n - q*a;
vS = vT; n = da;
vT = tY; dY = vZ;
}
#Justin,
Thanks. I was able to figure out how to print out the variables in each loop. I basically had to put my loop up with the GCD loop...that was it. 2 weeks worth of work and I had just to move where the loop was.
It works! I'm sorry but I'm doing a happy dance over here.
Here's a solution in Python that should be easily translatable into Java:
def euclid(x, y):
"""Given x < y, find a and b such that a * x + b * y = g where, g is the
gcd of x and y. Returns (a,b,g)."""
assert x < y
assert x >= 0
assert y > 0
if x == 0:
# gcd(0,y) = y
return (0, 1, y)
else:
# Write y as y = dx + r
d = y/x
r = y - d*x
# Compute for the simpler problem.
(a, b, g) = euclid(r, x)
# Then ar + bx = g -->
# a(y-dx) + bx = g -->
# ay - adx + bx = g -->
# (b-ad)x + ay = g
return (b-a*d, a, g)
def modinv(x, n):
(a, b, g) = euclid(x%n, n)
assert g == 1
# a * x + b * n = 1 therefore
# a * x = 1 (mod n)
return a%n
It uses the stack, but Euclid's algorithm takes O(log n) steps so you won't have a stack overflow unless your numbers are astronomically high. One could also translate it into a non-recursive version with some effort.