1. Trigonometric functions in Java

When we studied rounding numbers earlier, we got acquainted with the Math class and some of its methods. We will now look at this class in more detail.

As the name implies, the Math class contains methods for the mathematical operations most frequently used by programmers. Here are the most interesting ones:

Method Description
double sin(double d)
Returns the sine of the angle d, in radians
double cos(double d)
Returns the cosine of the angle d, in radians
double tan(double d)
Returns the tangent of the angle d, in radians
double asin(double d)
Returns the arcsine
double acos(double d)
Returns the arccosine
double atan(double d)
Returns the arctangent
double sinh(double d)
Returns the hyperbolic sine
double cosh(double d)
Returns the hyperbolic cosine
double tanh(double d)
Returns the hyperbolic tangent

The Math.sin(), Math.cos() and Math.tan() methods take an angle expressed in radians. To convert an angle from degrees to radians and vice versa, the Math class offers two special methods:

Method Description
double toRadians(double angdeg)
Converts an angle from degrees to radians
double toDegrees(double angrad)
Converts an angle from radians to degrees

By the way, in addition to methods, the Math class also has two constant variables (static fields of the class):

Constant Description
double Math.PI
The "Pi" constant is equal to 3.141592653589793
double Math.E
The "E" constant is equal to 2.718281828459045

All these functions can be very useful to you if you decide to write your own games, work with graphics, or simply calculate the length of a path on a map.

For example, if you want to calculate sin(45°), here's how you do it:

Math.sin( Math.toRadians(45) )

Here's an example:

public class Main
{
   public static int N = 10;

   public static void drawValue(double y)
   {
     int value = (int) (y * N) + N;
     for (int i = 0; i < 2 * N; i++)
     {
       char c = i == N ? '|': '.';
       if (i == value)
         c = '*';
       System.out.print(c);
     }
     System.out.println();
   }

   public static void main(String[] args)
   {
     for (int i = 0; i < 10 * N; i++)
     {
       double x = i * 1.0 / N;
       double y = Math.sin(x);
       drawValue(y);
     }
   }
}

1
Task
Module 1. Java Syntax,  level 11lesson 0
Locked
Integer literals
Four public fields, corresponding to the four integer types, are declared in the Solution class. When declared, these fields are initialized with various values stored in integer literals. But the program doesn't compile, and you need to fix it. To do this, make the fewest possible changes to the va

2. Algebraic functions in Java

In most cases, high school math is enough for a programmer: even sines and cosines are very rarely found in code. Most often they are needed when working with games, maps or game engines. 90% of programmers never encounter this.

But besides geometry, programmers sometimes have to use algebraic functions. And, of course, the Math class contains the most common ones:

Method Description
double sqrt(double a)
square root of a
double cbrt(double a)
cubic root of a
double pow(double a, double b)
exponentiation: ab
double exp(double a)
exponential (Euler's number raised to a power): ea
double log(double a)
natural logarithm of a: ln(a)
double log10(double a)
base-10 logarithm of a: log10(a)
double log1p(double x)
natural logarithm of x + 1: ln(x + 1)
double expm1(double x)
ex-1

If you want the square or cube root of a number, the sqrt(a) and cbrt(a) methods are at your service.

The square root can be calculated as follows:

Math.sqrt(2)

If you want to get a root of a higher power, then use the exponentiation method: a to the power of ¼ is the fourth root, etc.

Math.pow(2, 0.25)

For logarithms and exponents, there are the log(a) (natural logarithm) and exp(x) (exponential) methods. To calculate the base-10 logarithm, we have log10(a).

If you want the logarithm of a number b to base a, use this simple formula: loga(b) = ln(b) / ln(a)

Useful methods

If you are performing calculations involving very small values of x, then the last two functions — log1p() and expm1() — may be useful to you.

When adding very small and very large double variables, you will often find that very small values are simply ignored (discarded) as insignificant. In fact, this will happen if you use the log() and exp() methods. To solve this, programmers came up with functions that return only the "small significant part"

Example:

Suppose you want to calculate the natural logarithm of 1 + x, where x is 10-20. You can't simply pass this number to the log() method, since if you add 1 and 10-20, you get 1. 10-20 is such a small number that it will be completely discarded when the numbers are added.

Because mathematics often involves calculating the log() of numbers close to 1, programmers came up with a way to get around this problem: instead of passing the number itself to the method, pass only its difference from 1.


1
Task
Module 1. Java Syntax,  level 11lesson 0
Locked
Floating point literals
Seven public fields are declared and initialized in the Solution class. They are initialized with various values stored in floating point literals. But the program doesn't compile, and you need to fix it. To do this, change the field types so they match the values. Do not change the field names or v

3. Minimum and maximum

Two more useful functions are min(a, b) and max(a, b). As you probably already guessed, the first returns the minimum of two numbers:

Math.min(a, b)

And the second returns the maximum of two numbers:

Math.max(a, b)

Why do we need these functions when you can always write if or even use the ternary operator (a < b ? a: b)?

It's all about the readability of the code. Sometimes your code is overloaded with if statements and you want to use more compact notation. Let's compare:

Code Description
int x = 0;
if (x-5+y*20 < x*x+y*y)
   x = x-5+y*20;
else
   x = x*x+y*y;
Using an if-else statement (the longest way to write it)
int x = x-5+y*20 < x*x+y*y ? x-5+y*20 : x*x+y*y;
Using the ternary operator Cons:
- bulky code
- calculations are performed twice
int a = x-5+y*20;
int b = x*x+y*y;
int x = a < b ? a : b;
This is a great way to write it, but it's a little redundant
int x = Math.min(x-5+y*20, x*x+y*y);
Just right 🙂

4. Minimum and maximum of several numbers

There's another great way to use the min() and max() methods.

To calculate the minimum (or maximum) of several numbers or variables. It's very convenient to make nested calls to these methods.

Here's how to find the minimum of 3 numbers:

Math.min(a, Math.min(b, c))

So what? It's super convenient: calculate the minimum of two numbers, and then return the minimum of this number and the third number.

The minimum of four numbers is obtained in the same way:

Math.min(a, Math.min(b, Math.min(с, d)))

That said, we can write this formula a little more clearly:

Math.min(Math.min(a, b), Math.min(c, d))

It all works the same for the max() method.

Using the if-else operator or ternary operator would make these code snippets a little more cumbersome. But using the min() and max() methods is just perfect.


1
Task
Module 1. Java Syntax,  level 11lesson 0
Locked
String literals
A public string field is declared and initialized in the Solution class. But the string is too long and difficult to read. For better readability, you need to split it into 5 substrings and concatenate them with the "+" (string concatenation) operator, like this: - first line: "Always write code as