简体   繁体   中英

Generating random quadratic equations imposing condition for real numbers as roots

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM