Coding the Pythagoras theorem - java

Hi I am a beginner at java and I'm trying to write code to solve the Pythagoras' theorem. Here's what I've done so far however I keep getting errors with an illegal starter on line 14 as well as a "class, interface, or enum expected" error on line 31.
public class Pythagoras{
public static void main(String[] args){
double a1 = 5.2;
float a = (float)a1;
double b1 = 8.4;
float b = (float)b1;
double c1 = 0;
float c = (float)c1;
float resultC = (float)method (c);
System.out.println(resultC);
public static float method(float c){
if (c = 0){
float result = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
return result;
}
if (b = 0){
float result = Math.sqrt(Math.pow(c, 2) - Math.pow(a, 2));
return result;
}
if (a = 0){
float result = Math.sqrt(Math.pow(c, 2) - Math.pow(b, 2));
return result;
}
}
}
}

In java you cannot have a method defined inside another method. You would have to pull the method public static float method(float) out of main.
There are other flaws, for example:
Here: if (c = 0) you're assigning the value.
method has return statements inside ifs, but what if none is hit? Nothing is returned.
(float)method (c) you're casting to float something that is defined to be float.
Instead of double a1 = 5.2; float a = (float)a1; why don't you write float a = 5.2f?

Related

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

Find a number to the power of another number?

I am trying to write a function in java that finds the result of an operand raised to the power of another.
I can't use the pow function or any form of loop. What are any possible solutions? I tried "^" and that didn't work.
public static String raiseP(int op1, int op2){
int result = op1 ^ op2; //Doesn't Work
return result;
}
Would there be a way to do this using basic math?
I have written:
public static int pow(int x, int y, int n, int z){
if (y == n){
System.out.println(z);
return z;
}
else{
z = z*x;
n += 1;
pow(x,y,n,z);
return 0;
}
}
ex: pow(5,9,0,1) == 5^9
but am not allowed to use recursion.
Without being able to call Math.pow or using loops, the only other possibility is using recursion:
public int powerFunction(int base, int exponent) {
if(exponent < 0){ throw new IllegalArgumentException("unsupported negative pow"); }
if(exponent == 0){ return 1; }
else{
return base * powerFunction(base, exponent - 1);
}
}
Calling powerFunction(2, 3) will give you: 1 * 2 * 2 * 2 = 8
You could simply use that
pow(x,y) = exp(y*log(x))
which is also part of the implementation of the power function in the math library.
The recursion could help you:
public static int myPowerRec(int op1, int op2, int res) {
if (op2 == 0) {
return res;
}
else {
return (myPowerRec(op1, op2 - 1, op1 * res));
}
}
You will need to initialize res to 1 (myPowerRec(23, 2, 1) will give you 1 * 23 * 23).
This recursion is called tail recursion and will allow you to use this function without stack problem.
Be careful, you must check op2 value before.
Using a for loop:
public static int power(a, b) { // a ^ b
int p = 1;
for (int i = 1, i <= b; i++)
p *= a;
return p;
}

Calculating the Square Root using the Babylon Algorithm

For my assignment, I am supposed to use a 'Tolerance Flag'. Yet, I was able to complete the task with what I have so far. What does my teacher mean by tolerance flag?
Use a tolerance flag and make your variables a member of the double class.
const double TOLERANCE = 5e-8;
double x = 2.0;
_
My Work:
public class Sqrt_of_Two {
public static void main(String[] args) {
final double TOLERANCE = 5e-8;
double x = 2;
do{
x = (x + 2/x) / 2;
System.out.println(x);
}while( Math.ceil(x*x) > 2);
}
}
OUTPUT:
1.5
1.4166666666666665
1.4142156862745097
1.4142135623746899
1.414213562373095
I suppose it means something like:
while(Math.abs(x*x - 2) > TOLERANCE);
which outputs:
1.5
1.4166666666666665
1.4142156862745097
1.4142135623746899

Create a java program to solve quadratic equations

Solving a quadratic equation
I have the following written down so far. I am not sure on how to introduce the second method
public static void main(string args[]){
}
public static double quadraticEquationRoot1(int a, int b, int c) (){
}
if(Math.sqrt(Math.pow(b, 2) - 4*a*c) == 0)
{
return -b/(2*a);
} else {
int root1, root2;
root1 = (-b + Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a);
root2 = (-b - Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a);
return Math.max(root1, root2);
}
}
Firstly, your code won't compile--you have an extra } after the start of public static double quadraticEquationRoot1(int a, int b, int c) ().
Secondly, you aren't looking for the correct input types. If you want input of type double, make sure you declare the method appropriately. Also be careful of declaring things as int when they could be doubles (for example, root1 and root2).
Thirdly, I don't know why you have the if/else block--it would be better to simply skip it, and only use the code that is currently in the else part.
Finally, to address your original question: Simply create a separate method and use Math.min() instead of Math.max().
So, to recap in code:
public static void main(string args[]){
}
//Note that the inputs are now declared as doubles.
public static double quadraticEquationRoot1(double a, double b, double c) (){
double root1, root2; //This is now a double, too.
root1 = (-b + Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a);
root2 = (-b - Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a);
return Math.max(root1, root2);
}
public static double quadraticEquationRoot2(double a, double b, double c) (){
//Basically the same as the other method, but use Math.min() instead!
}
Well why don't you try to use the same exact algorithms but then use Math.min in your return statement?
Also, note that you're not taking into account whether or not $b$ is negative in your first if statement. In other words you simply return $-b / 2a$ but you don't check if $b$ is negative, if it isn't then this is actually the smaller of the two roots not the larger.
Sorry about that! I misinterpreted what was going on xD
package QuadraticEquation;
import javax.swing.*;
public class QuadraticEquation {
public static void main(String[] args) {
String a = JOptionPane.showInputDialog(" Enter operand a : ");
double aa = Double.parseDouble(a);
String b = JOptionPane.showInputDialog(" Enter operand b : ");
double bb = Double.parseDouble(b);
String c = JOptionPane.showInputDialog(" Enter operand c : ");
double cc = Double.parseDouble(c);
double temp = Math.sqrt(bb * bb - 4 * aa * cc);
double r1 = ( -bb + temp) / (2*aa);
double r2 = ( -bb -temp) / (2*aa);
if (temp > 0) {
JOptionPane.showMessageDialog(null, "the equation has two real roots" +"\n"+" the roots are : "+ r1+" and " +r2);
}
else if(temp ==0) {
JOptionPane.showMessageDialog(null, "the equation has one root"+ "\n"+ " The root is : " +(-bb /2 * aa));
}
else{
JOptionPane.showMessageDialog(null, "the equation has no real roots !!!");
}
}
}

Java: Check if two double values match on specific no of decimal places

Comparing those two values shall result in a "true":
53.9173333333333 53.9173
If you want a = 1.00001 and b = 0.99999 be identified as equal:
return Math.abs(a - b) < 1e-4;
Otherwise, if you want a = 1.00010 and b = 1.00019 be identified as equal, and both a and b are positive and not huge:
return Math.floor(a * 10000) == Math.floor(b * 10000);
// compare by == is fine here because both sides are integral values.
// double can represent integral values below 2**53 exactly.
Otherwise, use the truncate method as shown in Are there any functions for truncating a double in java?:
BigDecimal aa = new BigDecimal(a);
BigDecimal bb = new BigDecimal(b);
aa = aa.setScale(4, BigDecimal.ROUND_DOWN);
bb = bb.setScale(4, BigDecimal.ROUND_DOWN);
return aa.equals(bb);
here is the simple example if you still need this :)
public static boolean areEqualByThreeDecimalPlaces(double a, double b) {
a = a * 1000;
b = b * 1000;
int a1 = (int) a;
int b1 = (int) b;
if (a1 == b1) {
System.out.println("it works");
return true;
}
else
System.out.println("it doesn't work");
return false;
Naively:
if(Math.abs(a-b) < 0.0001)
However, that's not going to work correctly for all values. It's actually impossible to get it to work as long as you're using double, because double is implemented as binary fractons and does not even have decimal places.
You'll have to convert your values to String or BigDecimal to make meaningful tests about their decimal places.
You may want to read the Floating-Point Guide to improve your understanding of how floating point values work.
Apache commons has this:
org.apache.commons.math3.util.Precision equals(double x, double y, double eps)
epsilon would be the distance you would allow. Looks like yours would be 1e-5?
The source-code of this method looks like it uses Math.abs as suggested in other answers.
public static boolean areEqualByThreeDecimalPlaces(double a, double b){
if(a < 0 && b < 0) {
double c = Math.ceil(a * 1000) / 1000;
double d = Math.ceil(b * 1000) / 1000;
return c == d;
}
if(a > 0 && b > 0){
double c = Math.floor(a * 1000) / 1000;
double d = Math.floor(b * 1000) / 1000;
return c == d;
}
return a == b;
}
public static boolean areEqualByThreeDecimalPlaces(double a, double b) {
if(a > 0 && b >0){
return ((int)Math.floor(a * 1000) == (int)Math.floor(b * 1000));
}
else if (a < 0 && b <0) {
return ((int)Math.ceil(a * 1000) == (int)Math.ceil(b * 1000));
}
return a==b;
}
Thanks. I did it this way:
double lon = 23.567889;
BigDecimal bdLon = new BigDecimal(lon);
bdLon = bdLon.setScale(4, BigDecimal.ROUND_HALF_UP);
System.out.println(bdLon.doubleValue());
public static boolean areEqualBySixDecimalPlaces(double a, double b) {
int num1 = (int) (a * 1e6);
int num2 = (int) (b * 1e6);
return num1 == num2;
}
Casting up to desired digits shall be the simplest solution if you know the values
The solution to compare two double-digits up to three decimal places and return true or false might be:
public static boolean areEqualByThreeDecimalPlaces(double myFirstNumber , double mySecondNumber){
if (Math.abs(myFirstNumber - mySecondNumber) < 0.0009 ){
return true;
} else {
return false;
}
}

Categories