Trusted answers to developer questions

abhilash

Grokking Modern System Design Interview for Engineers & Managers

** scalb()** is a static method of the

`Math`

class in Java that scales a number by a specified power of $2$.To use the `scalb()`

method, you will need to import the `Math`

class into your program, as shown below.

```
import java.lang.Math;
```

The syntax of the `scalb()`

method is:

```
public static double scalb(double d, int scaleFactor)
```

The parameters of the `scalb()`

method are:

: A number of type`d`

`double`

to be scaled by a power of $2$.: The power of $2$ used to scale`scaleFactor`

`d`

.

The `scalb()`

method accepts two arguments, i.e., the number to be scaled (`x`

) and the scale factor (`y`

), and returns the result of the following expression.

```
x * (2 ** y)
```

Note: In the above expression, the

`**`

operator signifies raising $2$ to the power of`y`

.

The result has been accurately calculated when the exponent of the result is between `Double.MIN_EXPONENT`

and `Double.MAX_EXPONENT`

.

- If the first argument is
`NaN`

, then`NaN`

is returned. - If the first argument is infinite, then an infinity of the same sign is returned.
- If the first argument is zero, then a zero of the same sign is returned.

The code below shows how the `scalb()`

method works in Java.

import java.lang.Math;public class Main{public static void main(String[] args){double d = 23;int scaleFactor = 4;double result = Math.scalb(d, scaleFactor);System.out.printf("scalb(%f, %d) = %f", d, scaleFactor, result);System.out.println();d = -23;scaleFactor = 4;result = Math.scalb(d, scaleFactor);System.out.printf("scalb(%f, %d) = %f", d, scaleFactor, result);System.out.println();d = 23;scaleFactor = -4;result = Math.scalb(d, scaleFactor);System.out.printf("scalb(%f, %d) = %f", d, scaleFactor, result);System.out.println();}}

The code above uses 3 examples to demonstrate how the `scalb()`

method works.

In the first call to the `scalb()`

method in line $8$, `d`

is set to $23$, and `scaleFactor`

is set to $4$. As a result, the method returns $368$, i.e., `23 * (2 ^ 4) = 368`

The next call to the `scalb()`

method in line $14$ is identical, except this time `d`

is $-23$. Therefore, the method returns $-368$, i.e., `-23 * (2 ^ 4) = -368`

In the final call to the `scalb()`

method in line $20$, the `scaleFactor`

argument is $-4$. Consequently, the method returns $1.437500$, i.e., `23 * (2 ^ -4) = -368`

.

RELATED TAGS

java

math

communitycreator

CONTRIBUTOR

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Keep Exploring

Related Courses