in

Useful JavaScript math functions and how to use them

1664241202js math functions

[ad_1]

The built-in JavaScript Math object contains many convenience functions for performing various mathematical operations. Let’s see how they work and what they can be used for.

Math.max and Math.min

These functions do pretty much what you would expect them to do. These functions return the maximum or minimum value of the given list of arguments.

Math.max(1,2,3,4,5)
<< 5

Math.min(4,71,-7,2,1,0)
<< -7

argument all must be Number data type. Otherwise, NaN will return:

Math.max('a','b','c')
<< NaN

Math.min(5,"hello",6)
<< NaN

But be careful. JavaScript tries to: Force Value to number:

Math.min(5,true,6)
<< 1

In this example, the boolean true number is forced 1, which is why it is returned as the minimum value. If you’re not familiar with type coercion, it happens when the operands of an operator have different types. In this case, JavaScript will attempt to convert one operand to an equivalent value of the other operand’s type. For more information on type coercion, see JavaScript: Beginner to Ninja, 2nd Edition,Chapter 2.

The argument must be a list of numbers, not an array, but the spread operator (...) to unpack an array of numbers:

Math.max(...[8,4,2,1])
<< 8

of Math.max The function helps find high scores from a list of scores stored in an array.

const scores = [23,12,52,6,25,38,19,37,76,54,24]
const highScore = Math.max(...scores)
<< 76

of Math.min Functions help find the lowest prices on price comparison websites.

const prices = [19.99, 20.25, 18.57, 19,75, 25, 22.50]
const bestPrice = Math.min(...prices)
<< 18.57

Absolute value

Ann Absolute value is simply the size of the number, regardless of its size. This means that positive numbers stay the same and negative numbers lose the minus sign.of Math.abs A function computes the absolute value of its argument:

Math.abs(5)
<< 5

Math.abs(-42)
<< 42

Math.abs(-3.14159)
<< 3.14159

why do you want to do this?Well, sometimes you want to calculate difference It is calculated by subtracting the minimum value from the maximum value between two values, but often it is not possible to know in advance which of the two values ​​is the minimum value. To get around this, you can subtract the numbers in any order and get the absolute value.

const x = 5
const y = 8

const difference = Math.abs(x - y)
<< 3

A practical example would be a savings website that wants to know how much you can save by calculating the difference between two transactions. This is because we are dealing with live price data and we don’t know in advance which trade. Cheapest:

const dealA = 150
const dealB = 167

const saving = Math.abs(dealA - dealB)
<< 17

Math pow

Math.pow Perform power calculations such as:

3= 81

In the example above, 3 is base number and 4 are indexIt is read as “3 to the power of 4 is 81”.

This function takes two values, a base and an exponent, and returns the result of raising the base to the power of the exponent.

Math.pow(2,3)
<< 8

Math.pow(8,0)
<< 1

Math.pow(-1,-1)
<< -1

Math.pow Infix exponent operator (**) — introduced in ES2016 — does the exact same thing.

2 ** 3
<< 8

8 ** 0
<< 1

(-1) ** (-1)
<< -1

root calculation

A root is the inverse of a power. For example, 3 squared is 9, so the square root of 9 is 3.

Math.sqrt Can be used to return the square root of a number provided as an argument.

Math.sqrt(4)
<< 2

Math.sqrt(100)
<< 10

Math.sqrt(2)
<< 1.4142135623730951

This function returns NaN If a negative or non-numeric value is given as an argument:

Math.sqrt(-1)
<< NaN

Math.sqrt("four")
<< NaN

However, JavaScript tries to enforce types, so be careful.

Math.sqrt('4') 
<< 2

Math.sqrt(true)
<< 1

Math.cbrt Returns the cube root of a number. It accepts all numbers including negative numbers. It also tries to coerce types when non-numeric values ​​are used.If the value cannot be coerced to a number, return NaN:

Math.cbrt(1000)
<< 10

Math.cbrt(-1000)
<< -10

Math.cbrt("10")
<< 2.154434690031884

Math.cbrt(false)
<< 0

You can compute other roots using the exponentiation operator and fractional powers. For example, the 4th root of a number can be found by multiplying it by 1/4 (0.25). So the following code returns the 4th root of 625.

625 ** 0.25
<< 5

To find the 5th root of a number, multiply by 5 (or 0.2).

32 ** 0.2
<< 2

In general, to find the nth root of a number, raise it to the next power. 1/nSo to find the 6th root of 1 million, raise it to the 1/6th power.

1000000 ** (1/6)
<< 9.999999999999998

Note that there is rounding error here. The answer should be exactly 10. (For more on this rounding issue, see Guide to Rounding Numbers in JavaScript.)

Also note that you cannot find negative roots if the roots are even.this returns NaNSo, for example, you cannot try to find the 10th root of -7 (because 10 is even).

(-7) ** 0.1 
<< NaN

One reason to calculate roots is to calculate growth rate. For example, let’s say you want to multiply your profits by 10 by the end of the year. How much profit do you need to grow each month? To find this out, you need to calculate the 12th root of 10, or 10 to the 12th power.

10 ** (1/12)
<< 1.2115276586285884

This result indicates that a monthly growth rate of approximately 1.21 is required to multiply profits by 10 by the end of the year. In other words, you need to increase your profit by 21% each month to reach your goal.

logarithm and exponent

logarithm – or log for short – can be used to find the exponent of the calculation. For example, suppose we want to solve the equation

2ˣ = 100

In the above formula, x This is not an integer because 100 is not a power of 2. This can be solved using base 2 logarithms.

x = log²(100) = 6.64 (rounded to 2 d.p.)

of Math the object is log2 A method to perform this calculation:

Math.log2(100)
<< 6.643856189774724

again, log10 A way to perform the same calculation, but using 10 as the base.

Math.log10(100)
<< 2

This result shows that to get 100, you need to square 10.

There is another logging method. Math.logThis computes the natural logarithm using Euler’s number — e (about 2.7) — as a base. This may seem like an odd value, but it actually happens frequently in nature when exponential growth occurs, hence the name “natural logarithm”.

Math.log(10)
<< 4.605170185988092

Math.log(Math.E)
<< 1

The final calculation is the Euler number (e) — stored as a constant Math.E — must be a power of 1 to get itself. This makes sense. This is because the number that is a power of 1 is actually itself. Specifying 2 and 10 as arguments gives the same result. Math.log2 When Math.log10:

Math.log2(2)
<< 1

Math.log10(10)
<< 1

Why use logarithms? When dealing with exponentially growing data, it’s common to use a logarithmic scale to make it easier to see the rate of growth. His daily number of COVID-19 infections increased rapidly during the pandemic, so a logarithmic scale was often used.

If you are lucky enough to have a website whose popularity is skyrocketing (for example, doubling every day), use a logarithmic scale to see how popularity is growing before viewing the graph. We recommend that you consider indicating

hypotenuse

You may remember studying the Pythagorean theorem in school. This is the length of the longest side of a right triangle ( hypotenuse) can be found using the following formula:

= x² + y²

where x and y are the lengths of the remaining two sides.

of Math the object is hypot A method that computes the length of the hypotenuse given two other lengths as arguments. For example, if one side has length 3 and the other has length 4, you can use the following code to calculate the hypotenuse:

Math.hypot(3,4)
<< 5

But why is this useful? The hypotenuse is a measure of the shortest distance between two points. This means that if you know the x and y coordinates of two elements on the page, you can use this function to calculate the distance between them.

const ship = {x: 220, y: 100}
const boat = {x: 340, y: 50}

const distance = Math.hypot(ship.x - boat.x,ship.y - boat.y)

I hope this short summary is helpful and helps you get the most out of JavaScript’s Math object in your projects.

Related reading:

[ad_2]

Source link

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *

GIPHY App Key not set. Please check settings

    Lo2MQcpfnzchNRmLooMX88 1200 80

    Top website builders for WordPress in 2022

    smsf adviser logo

    Downsizer Bill Enters Senate