## Hypotenuse calculation using formulas with power and square root

Creating formulas that contain powers and square root.

## Learning Objectives

- Using formulas with powers and roots.
- Learning to build entire formula on right hand side only.

## Source Code

`class PowRoot`

{

public static void main(String[] args)

{

double b,h,hy ;

b=4.2;

h=3.3;

hy=Math.sqrt(Math.pow(b,2)+Math.pow(h,2));

hy=(int)(hy*100)/100.0;

System.out.println("RA triangle given base = "+b+" height = "+h);

System.out.println("Computed hypotenuse = "+hy);

}

}

## Run Output

## Code Understanding

** double b,h,hy ; b=4.2; h=3.3;**

Double variables declared and b and h are provided initial values. When you learn to collect input you can collect such values from user.

**hy=Math.sqrt(Math.pow(b,2)+Math.pow(h,2));**

This is java representation of a popular formula c^{2}=a^{2}+b^{2} . Since left hand side can not contain an expression so we build the entire formula on the right hand side only. For this the entire formula will be square root of a square + b square. For this reason the java math library metods sqrt() and pow() has been used. These methods are a part of java.lang.math package which is included by default in most programming environments as java.lang.* is usually imported by default.

**hy=(int)(hy*100)/100.0;**

This is done to truncate a high precision double computed value to 2 decimals. We multiply by 100 convert to integer and then divide by double 100.0 so that result is stored in double.

**System.out.println(“RA triangle given base = “+b+” height = “+h);**

** System.out.println(“Computed hypotenuse = “+hy);**

Given and computed values are printed.

## Code Notes

- The hypotenuse calculation will be approximate only due to limitations of precision of such calculations being in double precision. With the use of decimal place truncation or rounding off these values may be further approximated.
- Instead of truncation one can also use rounding off methods in java such by using DecimalFormat pattern based rounding or Math.round() methods. A good link to see such examples is –

https://www.mkyong.com/java/how-to-round-double-float-value-to-2-decimal-points-in-java/

**Suggested Filename(s): **PowRoot.java

sunmitra| Created: 6-Mar-2018 | Updated: 6-Mar-2018|