i deveoped a program to generate random quadratic equations and show their solutions. i took integers from an array containing numbers from -9 to 9, avoiding 0. I chose index by using Random object. but, i get invalid equations a lot , as square of B becomes more than 4AC, the solution is not a real number and i get "NaN" as my solutions. I want to set a condition such as square of B will always be greater than 4AC and the numbers will be taken from the array in such a manner.
my codes are:
import java.util.Random;
class number{
String equation, result;
public void set(){
int[] n = {-9,-8,-7,-6,-5,-4,-3,-2,-1,1,2,3,4,5,6,7,8,9};
Random r = new Random();
int x = r.nextInt(17);
int xx = r.nextInt(17);
int xxx = r.nextInt(17);
int a = n[x];
int b = n[xx];
int c = n[xxx];
double b1 = 0-b; double ac = 4*a*c ; double b2 = b*b; double rt1 = b2-ac;
double rt = Math.sqrt(rt1); double px1 = b1 + rt ; double px2 = b1 - rt;
double a1 = 2*a; double x1 = px1/a1; double x2 = px2/a1;
equation = String.format("The equation is (%d)X^2 + (%d)X + (%d) ",
a,b,c):
result = String.format("Roots are %.3f and %.3f" , x1, x2);
}
public String geteq(){
return equation; }
public String getres(){
return result; }
then in another class I just assigned them in JTextField in actionListener class of JButton.
Is there any way that, upon clicking the buttton, it will automatically repeat the set() method until square of B is greater than 4AC ?
You can try this:
do {
a = n[r.nextInt(17)];
b = n[r.nextInt(17)];
c = n[r.nextInt(17)];
} while (b*b<=4*a*c);
This way, you can only have real solutions
Related
My program keeps hitting a brickwall when I try to run the code. I get the error "Exception in thread "main" java.lang.Error: Unresolved compilation problem: DfinalResult cannot be resolved to a variable". I have tried to read other solutions but so far no luck. Any adivce on what im doing wrong to get this code to run. Also, it should be noted that the issue occurs when I try to call the result from one of my methods to a println.
-Liam
P.s. If the numbers dont work out right now that's okay I havent been able to test it since I cant run it lol.
import java.util.Scanner;
public class mathMecklenburg {
//note: i have a very good idea don't forget it
public static void main(String[] args) {
System.out.println("Enter an integer between 1 and 10 to be used as the first value: ");
Scanner scanint = new Scanner(System.in);
int x = scanint.nextInt();
System.out.println("Enter an integer between 1 and 10 to be used as the second value: ");
int y = scanint.nextInt();
System.out.println("Enter an integer between 1 and 10 to be used as the third value: ");
int z = scanint.nextInt(); //x,y,z will be input values from person
scanint.close();
double A1 = operationOne(x); //A1 is just operation 1 only using x. made double maybe for later difficulty
System.out.println("The answer to part one of the problems is: " + A1);
double A2 = operationTwo(x,y); // A2 is operation 2 using x and y
System.out.println("The answer to part two of the problems is: " + A2);
double A3 = operationThree(x,y,z); //A3 is operation 3 is using x,y,z. make something difficult here
System.out.println("The answer to part three of the problems is: " + A3); //these print text then A3
int IfinalResult = (int) DfinalResult;
System.out.println("The double trouble answer is " + IfinalResult);
//summary of the mentioned declared stuff in this part:
//x,y,z are all input numbers from the person
//A1, A2, A3 are the holders for each operations output i
//currently all of them are same data types maybe make more confusing later
//final answer should be fun also make a method for final answer later to clean up code
// finalAnswer = (Create an equation that utilizes all of the arithmetic operators and all three answers)
//for me to check that numbers work out
//System.out.println("The final answer is:" + IfinalResult); //put the result from the final method here for print);
}
//side note: make sure all the first 3 operations give whole numbers no decimals yet
public static int operationOne(int x) {
int answerOne;
answerOne = x+2;
// answerOne = (Create an equation that utilizes all of the arithmetic operators with the one input parameter)
return answerOne;
}
public static int operationTwo(int x, int y) {
int answerTwo;
answerTwo = x + y;
// answerOne = (Create an equation that utilizes all of the arithmetic operators with both input parameters)
return answerTwo;
}
public static int operationThree(int x, int y, int z) {
int answerThree;
answerThree = x + y + z;
// answerThree = (Create an equation that utilizes all of the arithmetic operators using all three input parameters)
return answerThree;
}
public static double doubleTrouble(int x, int y, int z, int A1, int A2, int A3, int IfinalResult) { //i thought the method name was funny
double Fx = Math.log(A1 - (A2 + A3)); //oops :) final answer x (Fx)
return (int) Fx;
double Fy = Math.exp(7); //final answer y (Fy)
return Fy;
double Fz = Math.asin(Fy)/(200); //final answer z (Fz)
return Fz;
double Fz1 = Math.exp(Fx+Fy+Fz);
double F1 = (Fx+Fy+Fz)*(java.lang.Math.PI)+A1;
double F2 = F1/(x)+(y)/(x)+5*(x+y);
double F3 = F1+F2-A1;
double DfinalResult = F1+F2+2*(F3*Fz1);
}
}
The variable DfinalResult cant be seen outside of the method doubleTrouble and you are using in on the main method.
there is 4 errors in your program
1: there is no variable called. DfinalResult
2: I don't know if you know but when you use the command return it dosn't continue with the code
public static double doubleTrouble(int x, int y, int z, int A1, int A2, int A3, int IfinalResult) {
double Fx = Math.log(A1 - (A2 + A3)); //oops :) final answer x (Fx)
return (int) Fx; "Here you return so the next line wouldn't be executed"
double Fy = Math.exp(7); //final answer y (Fy)
return Fy;
double Fz = Math.asin(Fy)/(200); //final answer z (Fz)
return Fz;
double Fz1 = Math.exp(Fx+Fy+Fz);
double F1 = (Fx+Fy+Fz)*(java.lang.Math.PI)+A1;
double F2 = F1/(x)+(y)/(x)+5*(x+y);
double F3 = F1+F2-A1;
double DfinalResult = F1+F2+2*(F3*Fz1);
}
doubleTrouble() method contains a lot of errors.
You can't write return statements in between.
You didn't declare DfinalResult variable in the main method.
That's why the code didn't compile.
I have fixed the error. Update to this :
public class Sample {
public static void main(String[] args) {
System.out.println("Enter an integer between 1 and 10 to be used as the first value: ");
Scanner scanint = new Scanner(System.in);
int x = scanint.nextInt();
System.out.println("Enter an integer between 1 and 10 to be used as the second value: ");
int y = scanint.nextInt();
System.out.println("Enter an integer between 1 and 10 to be used as the third value: ");
int z = scanint.nextInt(); // x,y,z will be input values from person
scanint.close();
double A1 = operationOne(x); // A1 is just operation 1 only using x. made double maybe for later difficulty
System.out.println("The answer to part one of the problems is: " + A1);
double A2 = operationTwo(x, y); // A2 is operation 2 using x and y
System.out.println("The answer to part two of the problems is: " + A2);
double A3 = operationThree(x, y, z); // A3 is operation 3 is using x,y,z. make something difficult here
System.out.println("The answer to part three of the problems is: " + A3); // these print text then A3
int IfinalResult = (int) doubleTrouble(x, y, z, A1, A2, A3);
System.out.println("The double trouble answer is " + IfinalResult);
}
// side note: make sure all the first 3 operations give whole numbers no
// decimals yet
public static int operationOne(int x) {
int answerOne;
answerOne = x + 2;
// answerOne = (Create an equation that utilizes all of the arithmetic operators
// with the one input parameter)
return answerOne;
}
public static int operationTwo(int x, int y) {
int answerTwo;
answerTwo = x + y;
// answerOne = (Create an equation that utilizes all of the arithmetic operators
// with both input parameters)
return answerTwo;
}
public static int operationThree(int x, int y, int z) {
int answerThree;
answerThree = x + y + z;
// answerThree = (Create an equation that utilizes all of the arithmetic
// operators using all three input parameters)
return answerThree;
}
public static double doubleTrouble(int x, int y, int z, double a1, double a2, double a3) {
double Fx = Math.log(a1 - (a2 + a3)); // oops :) final answer x (Fx)
double Fy = Math.exp(7); // final answer y (Fy)
double Fz = Math.asin(Fy) / (200); // final answer z (Fz)
double Fz1 = Math.exp(Fx + Fy + Fz);
double F1 = (Fx + Fy + Fz) * (java.lang.Math.PI) + a1;
double F2 = F1 / (x) + (y) / (x) + 5 * (x + y);
double F3 = F1 + F2 - a1;
double DfinalResult = F1 + F2 + 2 * (F3 * Fz1);
return DfinalResult;
}
}
This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 3 years ago.
I am trying to write a formula for one of my functions where I need to raise my X to power of Y. The values I am working with are really small and will get rounded up as soon as I use pow function of Math, BigInteger and BigDecimal.
For example if I use the following values it will return 1000 whereas it should return 1006.931669!
T0 = 1000, TN = 1, k = 1, N = 1000
double X = (finalTemp/initialTemp);
double A = Math.pow(X, (k/n));
double tk = initialTemp * A;
They are being divided in integer arithmetics. So dividing integer a by integer b you get how many times b fits into a, If the types of the operands are double, then "real" division is performed.
double X = (finalTemp/(double)initialTemp);
double A = Math.pow(X, (k/(double)n));
double tk = initialTemp * A;
the output is correct according to calculator
public class Main
{
public static void main(String[] args) {
double finalTemp = 1.0;
double initialTemp = 1000.0;
double k = 1.0;
double n = 1000.0;
double X = (finalTemp/initialTemp);
double A = Math.pow(X, (k/n));
double tk = initialTemp * A;
System.out.println(tk);
}
}
output is 993.1160484209338
Problem:
Write a program that reads the lengths of the sides of a triangle from the user. Compare the area of the triangle using Heron's formula, in which s represents half of the perimeter of the triangle and a,b, and c represent the lengths of the three sides.
import java.util.Scanner;
public class AreaOfTriangle
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
final double NUM_ONE = 0.5;
int a, b, c;
double s, area;
System.out.print("Enter side a: ");
a = scan.nextInt();
System.out.print("Enter side b: ");
b = scan.nextInt();
System.out.print("Enter side c: ");
c = scan.nextInt();
s = NUM_ONE * (a + b + c);
area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
System.out.println("\nThe area of the triangle = " + area);
}
}
The formula is correct, but s*(s-a)*(s-b)*(s-c) could end up being very slightly negative depending on the inputs (due to floating point imprecision). You should test this prior to taking the sqrt, and return zero in that instance.
Math.sqrt on a negative number will return NaN.
Because in some cases with your code you end up with a negative value in your sqrt call:
a = 1;
b = 2;
c = 5;
s = NUM_ONE * (a + b + c);
Here s = 4.0 and then your sqrt parameter is 4*3*2*-1 which is negative
Should you use Math.sqrt(Math.abs(...)) instead ?
This question already has answers here:
Fastest way to sort 3 values in Java [closed]
(3 answers)
Closed 7 years ago.
I will only take 3 values from the user, so there are only 3 possible answers. You can also assume that the user won't enter 0 three times and that it wouldn't matter if they entered the same value three times. I can create my own stuff for those scenarios (and I already have).
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Triangles
{
public static void main (String[]args) throws IOException
{
String a = "You have an";
String b = "triangle";
double l;
Scanner lengthinput = new Scanner(System.in);
double h;
Scanner heightinput = new Scanner(System.in);
double w;
Scanner widthinput = new Scanner(System.in);
System.out.println("Enter the length.");
l = lengthinput.nextDouble();
System.out.println("Enter the height.");
h = heightinput.nextDouble();
System.out.println("Enter the width.");
w = widthinput.nextDouble();
double max = l;
if (w > max) max = w;
if (h > max) {max = h;
The reason I'm struggling is because of the following:
I know the max, now I should just replicate the max code to create a minimum (since that's all I've learned just yet (intro CS class)). However, how would I know how to exclude the minimum value from being the one that I randomly select? Then the same for the medium value.
You can find the min, medium and max of three values like this:
double a = ...;
double b = ...;
double c = ...;
if (a > b) {
double swap = a;
a = b;
b = swap;
}
if (b > c) {
double swap = b;
b = c;
c = swap;
}
if (a > b) {
double swap = a;
a = b;
b = swap;
}
System.out.println("Min: "+a);
System.out.println("Med: "+b);
System.out.println("Max: "+c);
You can try something like below:
float l = 2.0f;
float h = 3.0f;
float w = 1.5f;
float[] arr = new float[] {l, h, w};
Arrays.sort(arr);
System.out.println("Min: " + arr[0] + ", Medium: " + arr[1] + ", Max: " + arr[2]);
I am writing a program to calculate Feigenbaum's constant using the Logistics equation by finding superstable values and then using the ratio of these superstable values to calculate the constant.
I use BigDecimals for almost all of my values so that I can maintain the necessary level of precision during the calculation of the constant.
I am adapting my code from the C++ code on pages 30-35 of the following file: http://webcache.googleusercontent.com/search?q=cache:xabTioRiF0IJ:home.simula.no/~logg/pub/reports/chaos_hw1.ps.gz+&cd=21&hl=en&ct=clnk&gl=us
I doubt what the program does even matters to my question. I run the program, and it seems to be working. The output i get for the first 4 superstable values and the first 2 d's is what is expected, but then after displaying these 4 rows, the program seems to just halt. I don't get an exception, but even after waiting for 30 minutes no more calculations are outputted. I can't figure out what exactly is causing it, because the calculation time should be about the same for each row, yet it obviously is not. Here is my output:
Feigenbaum constant calculation (using superstable points):
j a d
-----------------------------------------------------
1 2.0 N/A
2 3.23606797749979 N/A
4 3.4985616993277016 4.708943013540503
8 3.554640862768825 4.680770998010695
And here is my code:
import java.math.*;
// If there is a stable cycle, the iterates of 1/2 converge to the cycle.
// This was proved by Fatou and Julia.
// (What's special about x = 1/2 is that it is the critical point, the point at which the logistic map's derivative is 0.)
// Source: http://classes.yale.edu/fractals/chaos/Cycles/LogisticCycles/CycleGeneology.html
public class Feigenbaum4
{
public static BigDecimal r[] = new BigDecimal[19];
public static int iter = 0;
public static int iter1 = 20; // Iterations for tolerance level 1
public static int iter2 = 10; // Iterations for tolerance level 2
public static BigDecimal tol1 = new BigDecimal("2E-31"); // Tolerance for convergence level 1
public static BigDecimal tol2 = new BigDecimal("2E-27"); // Tolerance for convergence level 2
public static BigDecimal step = new BigDecimal("0.01"); // step when looking for second superstable a
public static BigDecimal x0 = new BigDecimal(".5");
public static BigDecimal aZero = new BigDecimal("2.0");
public static void main(String [] args)
{
System.out.println("Feigenbaum constant calculation (using superstable points):");
System.out.println("j\t\ta\t\t\td");
System.out.println("-----------------------------------------------------");
int n = 20;
if (FindFirstTwo())
{
FindRoots(n);
}
}
public static BigDecimal F(BigDecimal a, BigDecimal x)
{
BigDecimal temp = new BigDecimal("1");
temp = temp.subtract(x);
BigDecimal ans = (a.multiply(x.multiply(temp)));
return ans;
}
public static BigDecimal Dfdx(BigDecimal a, BigDecimal x)
{
BigDecimal ans = (a.subtract(x.multiply(a.multiply(new BigDecimal("2")))));
return ans;
}
public static BigDecimal Dfda(BigDecimal x)
{
BigDecimal temp = new BigDecimal("1");
temp = temp.subtract(x);
BigDecimal ans = (x.multiply(temp));
return ans;
}
public static BigDecimal NewtonStep(BigDecimal a, BigDecimal x, int n)
{
// This function returns the Newton step for finding the root, a,
// of fn(x,a) - x = 0 for a fixed x = X
BigDecimal fval = F(a, x);
BigDecimal dval = Dfda(x);
for (int i = 1; i < n; i++)
{
dval = Dfda(fval).add(Dfdx(a, fval).multiply(dval));
fval = F(a, fval);
}
BigDecimal ans = fval.subtract(x);
ans = ans.divide(dval, MathContext.DECIMAL64);
ans = ans.negate();
return ans;
}
public static BigDecimal Root(BigDecimal a0, int n)
{
// Find the root a of fn(x,a) - x = 0 for fixed x = X
// with Newton’s method. The initial guess is a0.
//
// On return iter is the number of iterations if
// the root was found. If not, iter is -1.
BigDecimal a = a0;
BigDecimal a_old = a0;
BigDecimal ans;
// First iter1 iterations with a stricter criterion,
// tol1 < tol2
for (iter = 0; iter < iter1; iter++)
{
a = a.add(NewtonStep(a, x0, n));
// check for convergence
BigDecimal temp = a.subtract(a_old);
temp = temp.divide(a_old, MathContext.DECIMAL64);
ans = temp.abs();
if (ans.compareTo(tol1) < 0)
{
return a;
}
a_old = a;
}
// If this doesn't work, do another iter2 iterations
// with the larger tolerance tol2
for (; iter < (iter1 + iter2); iter++)
{
a = a.add(NewtonStep(a, x0, n));
// check for convergence
BigDecimal temp = a.subtract(a_old);
temp = temp.divide(a_old, MathContext.DECIMAL64);
ans = temp.abs();
if (ans.compareTo(tol2) < 0)
{
return a;
}
a_old = a;
}
BigDecimal temp2 = a.subtract(a_old);
temp2 = temp2.divide(a_old, MathContext.DECIMAL64);
ans = temp2.abs();
// If not out at this point, iterations did not converge
System.out.println("Error: Iterations did not converge,");
System.out.println("residual = " + ans.toString());
iter = -1;
return a;
}
public static boolean FindFirstTwo()
{
BigDecimal guess = aZero;
BigDecimal r0;
BigDecimal r1;
while (true)
{
r0 = Root(guess, 1);
r1 = Root(guess, 2);
if (iter == -1)
{
System.out.println("Error: Unable to find first two superstable orbits");
return false;
}
BigDecimal temp = r0.add(tol1.multiply(new BigDecimal ("2")));
if (temp.compareTo(r1) < 0)
{
System.out.println("1\t\t" + r0.doubleValue() + "\t\t\tN/A");
System.out.println("2\t" + r1.doubleValue() + "\t\tN/A");
r[0] = r0;
r[1] = r1;
return true;
}
guess = guess.add(step);
}
}
public static void FindRoots(int n)
{
int n1 = 4;
BigDecimal delta = new BigDecimal(4.0);
BigDecimal guess;
for (int i = 2; i < n; i++)
{
// Computation
BigDecimal temp = (r[i-1].subtract(r[i-2])).divide(delta, MathContext.DECIMAL64);
guess = r[i-1].add(temp);
r[i] = Root(guess, n1);
BigDecimal temp2 = r[i-1].subtract(r[i-2]);
BigDecimal temp3 = r[i].subtract(r[i-1]);
delta = temp2.divide(temp3, MathContext.DECIMAL64);
// Output
System.out.println(n1 + "\t" + r[i].doubleValue() + "\t" + delta.doubleValue());
// Step to next superstable orbit
n1 = n1 * 2;
}
}
}
EDIT:
Phil Steitz's Answer essentially solved my problem. I looked at some thread dumps, and after doing a bit of research to try and understand them, and compiling my program with debugging info, I was able to find that the main thread was stalling at the line:
dval = Dfda(fval).add(Dfdx(a, fval).multiply(dval));
as Phil Steit's said, by using
MathContext.DECIMAL128
in not only this line:
dval = Dfda(fval).add(Dfdx(a, fval).multiply(dval));
but also in my multiplication operations in the methods F, Dfda, and Dfdx, I was able to get my code to work properly.
I used DECIMAL128 because the smaller precision made the calculation non-functional, because I compare them to such low numbers for the tolerance check.
I think that what is going on here is that when n is larger than about 10, your NewtonStep method becomes very slow because none of your multiply invocations limit the scale by providing a MathContext. When no MathContext is provided, the result of a multiply gets the sum of the scales of the multiplicands. With the code above, the scales of dval and fval inside the for loop in NewtonStep get very large for large n, resulting in very slow multiplications in this method and the methods that it calls. Try specifying MathContext.DECIMAL64 (or something else) in the multiply activations as you do for the divides.