It may be necessary in a program to use common mathematical functions such as the sine, square root, or log of a number. There are some standard methods Java provides to do this simply. To calculate y = x2 it is easiest to use the expression y = x*x, however for higher powers of x this is awkward, so in general y = xn is calculated using y = Math.pow(x,n).
The values or variables placed in the round brackets, (), are known as arguments.
These useful methods providing mathematical functions exist:
Math.E // e as a double
Math.PI // pi as a double
Math.sin(x) // sine of x
Math.cos(x) // cosine of x
Math.tan(x) // tangent of x
Math.asin(x) // arcsine of x
Math.acos(x) // arcsine of x
Math.atan(x // arctangent of x
Math.exp(x) // exponential of x
Math.log(x) // natural logarithm of x
Math.pow(x,n) // x raised to the power n (both double)
Math.sqrt(x) // square root of x
Math.random() // random double between 0.0 and 1.0 (uniform distribution)
// requires no argument
Math.abs(x) // the absolute value of x, works for int, long, float and
// double values, returning value of the same type
Except Math.abs() these mathematical functions all give result
values of type double. They also all take a double variables or
values as their arguments -- both x and n in the
above are double variables. Note that Math.pow() requires two
arguments, whereas Math.random() requires none, although
the brackets must still be included. Using Math.abs() is
slightly different -- using it on a float variable will give a float
value, on an int variable will return an int value, and so on.
Note that all the trigonometric functions work in radians.
Exercise 2.1
Write a program that reads in a value for an angle from the keyboard,
computes and writes out the sine and cosine and, as a check, the value
of
sin2x + cos2x for that angle. The value of
sin2x + cos2x, of
course, should be very close to 1. In your laboratory notebook,
record the results of entering the angles 3.5 and 2.3e-3. You should
use variables of type double and include all significant figures in
your written answer.
Stick a print out of your program in your lab notebook.