简体   繁体   English

生成以实数为根的条件的随机二次方程

[英]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. 我从包含从-9到9的数字的数组中获取整数,避免使用0。我通过使用Random对象选择了index。 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. 但是,当B的平方变得大于4AC时,我得到了很多无效方程,解决方案不是一个实数,我得到了“ NaN”作为我的解决方案。 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. 我想设置一个条件,例如B的平方将始终大于4AC,并且将以这种方式从数组中获取数字。 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. 然后在另一个类中,我只是在JButton的actionListener类的JTextField中分配了它们。 Is there any way that, upon clicking the buttton, it will automatically repeat the set() method until square of B is greater than 4AC ? 有什么方法可以在单击按钮后自动重复set()方法,直到B的平方大于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 这样,您只能拥有真正的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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