Модуль числа в python

Comentários

O comportamento deste método segue o padrão IEEE 754, seção 4.The behavior of this method follows IEEE Standard 754, section 4. Este tipo de arredondamento às vezes é chamado de arredondamento para negativo infinito.This kind of rounding is sometimes called rounding toward negative infinity.

Floor(Double)

Retorna o maior valor integral menor ou igual ao número de ponto flutuante de precisão dupla especificado.Returns the largest integral value less than or equal to the specified double-precision floating-point number.

d

Double

Um número de ponto flutuante de precisão dupla.A double-precision floating-point number.

Retornos

Double

O maior valor integral menor ou igual a .The largest integral value less than or equal to . Se for igual a NaN, NegativeInfinity ou PositiveInfinity, esse valor será retornado.If is equal to NaN, NegativeInfinity, or PositiveInfinity, that value is returned.

Exemplos

O exemplo a seguir ilustra o método e o contrasta com o método.The following example illustrates the method and contrasts it with the method.

Comentários

O comportamento deste método segue o padrão IEEE 754, seção 4.The behavior of this method follows IEEE Standard 754, section 4. Este tipo de arredondamento às vezes é chamado de arredondamento para negativo infinito.This kind of rounding is sometimes called rounding toward negative infinity. Em outras palavras, se for positivo, qualquer componente fracionário será truncado.In other words, if is positive, any fractional component is truncated. Se for negativo, a presença de qualquer componente fracionário fará com que ele seja arredondado para o número inteiro menor.If is negative, the presence of any fractional component causes it to be rounded to the smaller integer. A operação desse método difere do Ceiling método, que dá suporte ao arredondamento em direção ao infinito positivo.The operation of this method differs from the Ceiling method, which supports rounding toward positive infinity.

A partir do Visual Basic 15,8, o desempenho da conversão de duplo para inteiro será otimizado se você passar o valor retornado pelo método para qualquer uma das funções de conversão integralou se o valor Double retornado por for automaticamente convertido em um inteiro com Option Strict definida como off.Starting with Visual Basic 15.8, the performance of Double-to-integer conversion is optimized if you pass the value returned by the method to the any of the integral conversion functions, or if the Double value returned by is automatically converted to an integer with Option Strict set to Off. Essa otimização permite que o código seja executado mais rapidamente – até duas vezes mais rápido para o código que faz um grande número de conversões para tipos de inteiro.This optimization allows code to run faster — up to twice as fast for code that does a large number of conversions to integer types. O exemplo a seguir ilustra essas conversões otimizadas:The following example illustrates such optimized conversions:

Usage #

Units can be created using the function . This function accepts
either a single string argument containing a value and unit, or two arguments,
the first being a numeric value and the second a string containing a unit.
Most units support prefixes like or , and many units have both a
full name and an abbreviation. The returned object is a .

Syntax:

Example usage:

Use care when creating a unit with multiple terms in the denominator. Implicit multiplication has the same operator precedence as explicit multiplication and division, which means these three expressions are identical:

But this expression, which omits the second between and , results in the wrong value:

Custom argument parsing #

The expression parser of math.js has support for letting functions
parse and evaluate arguments themselves, instead of calling them with
evaluated arguments. This is useful for example when creating a function
like or , where some of the
arguments need to be processed in a special way. In these cases, the expression
will be evaluated repeatedly by the function, and is not evaluated
but used to specify the variable looping over the function .

Functions having a property with value are treated in a special
way by the expression parser: they will be invoked with unevaluated arguments,
allowing the function to process the arguments in a customized way. Raw
functions are called as:

Where :

  • is an Array with nodes of the parsed arguments.
  • is the math namespace against which the expression was compiled.
  • is a shallow copy of the object provided when evaluating
    the expression, optionally extended with nested variables like a function
    parameter of in a custom defined function like .

Raw functions must be imported in the namespace, as they need to be
processed at compile time. They are not supported when passed via a scope
at evaluation time.

A simple example:

Квадратный корень

Положительное число

Именно на работу с неотрицательными числами «заточена» функция

Если число больше или равно нулю, то неважно, какой у него тип. Вы можете извлекать корень из целых чисел:

А можете – из вещественных:

Легко проверить корректность полученных результатов с помощью обратной операции возведения в степень:

Отрицательное число

Функция не принимает отрицательных аргументов. Только положительные целые числа, вещественные числа и ноль.

Такая работа функции идёт вразрез с математическим определением. В математике корень спокойно извлекается из чисел меньше 0. Вот только результат получается комплексным, а таким он нужен для относительно узкого круга реальных задач, вроде расчетов в сфере электроэнергетики или физики волновых явлений.

Поэтому, если передадите отрицательное число в , то получите ошибку:

Тригонометрические функции в Python

Модуль math в Python поддерживает все тригонометрические функции. Самые популярные представлены ниже:

  • : Возвращает синус в радианах;
  • : Возвращает косинус в радианах;
  • : Возвращает тангенс в радианах;
  • : Возвращает инвертированный синус. Аналогичным образом работают и ;
  • : Конвертирует угол из радиан в градусы;
  • : Конвертирует угол из градусов в радианы.

Рассмотрим следующий пример:

Python

import math

angle_In_Degrees = 62
angle_In_Radians = math.radians(angle_In_Degrees)

print(‘Значение угла:’, angle_In_Radians)
print(‘sin(x) равен:’, math.sin(angle_In_Radians))
print(‘tan(x) равен:’, math.tan(angle_In_Radians))
print(‘cos(x) равен:’, math.cos(angle_In_Radians))

1
2
3
4
5
6
7
8
9

importmath

angle_In_Degrees=62

angle_In_Radians=math.radians(angle_In_Degrees)

print(‘Значение угла:’,angle_In_Radians)

print(‘sin(x) равен:’,math.sin(angle_In_Radians))

print(‘tan(x) равен:’,math.tan(angle_In_Radians))

print(‘cos(x) равен:’,math.cos(angle_In_Radians))

Вывод

Shell

Значение угла: 1.0821041362364843
sin(x) равен: 0.8829475928589269
tan(x) равен: 1.8807264653463318
cos(x) равен: 0.46947156278589086

1
2
3
4

Значениеугла1.0821041362364843

sin(x)равен0.8829475928589269

tan(x)равен1.8807264653463318

cos(x)равен0.46947156278589086

Обратите внимание, что вначале мы конвертировали значение угла из градусов в радианы для осуществления дальнейших операций

Решение реальной задачи с использованием sqrt

Корень – дитя геометрии. Когда Пифагор доказал свою знаменитую теорему, людям тут же захотелось вычислять стороны треугольников, проверять прямоту внешних углов и сооружать лестницы нужной длины.

Соотношение a2 + b2 = c2, где «a» и «b» – катеты, а «c» – гипотенуза – естественным образом требует извлекать корни при поиске неизвестной стороны. Python-а под рукой у древних греков и вавилонян не было, поэтому считать приходилось методом приближений. Жизнь стала проще, но расчет теоремы Пифагора никто не отменял и в XXI веке.

Решим задачку про вышку сотовой связи. Заказчик требует рассчитать высоту сооружения, чтобы радиус покрытия был 23 километра. Мы неспешно отходим на заданное расстояние от предполагаемого места строительства и задумчиво смотрим под ноги. В голове появляются очертания треугольника с вершинами:

  1. Ваше местоположение;
  2. Центр Земли;
  3. Пиковая высота вышки;

Модель готова, приступаем к написанию кода:

Расчёт выполнен, результат заказчику предоставлен. Можно идти пить чай и радоваться тому, что теперь ещё больше людей смогут звонить родным и сидеть в интернете.

Custom HTML, LaTeX and string output #

All expression nodes have a method and to output an expression respectively in HTML or LaTex format or as regular text .
The functions , and accept an argument to customise output. This object is of the following form:

Parenthesis

The option changes the way parentheses are used in the output. There are three options available:

  • Keep the parentheses from the input and display them as is. This is the default.
  • Only display parentheses that are necessary. Mathjs tries to get rid of as much parentheses as possible.
  • Display all parentheses that are given by the structure of the node tree. This makes the output precedence unambiguous.

There’s two ways of passing callbacks:

  1. Pass an object that maps function names to callbacks. Those callbacks will be used for FunctionNodes with
    functions of that name.
  2. Pass a function to . This function will then be used for every node.

Handler

You can provide the and functions of an expression with your own custom handlers that override the internal behaviour. This is especially useful to provide LaTeX/string output for your own custom functions. This can be done in two ways:

  1. Pass an object that maps function names to callbacks. Those callbacks will be used for FunctionNodes that contain functions with that name.
  2. Pass a callback directly. This callback will run for every node, so you can replace the output of anything you like.

A callback function has the following form:

Where is the object passed to //. Don’t forget to pass this on to the child nodes, and is a reference to the current node.

If a callback returns nothing, the standard output will be used. If your callback returns a string, this string will be used.

Although the following examples use , it works for and in the same way

Examples for option 2:

Another example in conjunction with custom functions:

Implicit multiplication

You can change the way that implicit multiplication is converted to a string or LaTeX. The two options are , to not show a multiplication operator for implicit multiplication and to show it.

Example:

Factory functions #

Regular JavaScript functions can be imported in math.js using :

The function can be stored in a separate file:

Which can be imported like:

An issue arises when needs functionality from math.js:
it doesn’t have access to the current instance of math.js when in a separate file.
Factory functions can be used to solve this issue. A factory function allows to inject dependencies into a function when creating it.

A syntax of factory function is:

where:

  • is the name of the created function.
  • is an array with names of the dependent functions.
  • is a function which creates the function.
    An object with the dependencies is passed as first argument.
  • An optional object which can contain any meta data you want.
    This will be attached as a property on the created function.
    Known meta data properties used by the mathjs instance are:

    • If true, the created function is supposed to be a
      class, and for example will not be exposed in the expression parser
      for security reasons.
    • . By default, everything is imported lazily by .
      only as soon as the imported function or constant is actually used, it
      will be constructed. A function can be forced to be created immediately
      by setting in the meta data.
    • . If true, the created function is imported
      as a transform function. It will not be imported in itself, only
      in the internal namespace that is used by the
      expression parser.
    • . If true, the imported factory will be
      created again when there is a change in the configuration. This is for
      example used for the constants like , which is different depending
      on the configsetting which can be numbers or BigNumbers.

Here an example of a factory function which depends on :

You may wonder why you would inject functions and
instead of just doing these calculations inside the function itself. The
reason is that this makes the factory function work for
different implementations: numbers, BigNumbers, units, etc.

Parser #

In addition to the static functions and
, math.js contains a parser with functions and
, which automatically keeps a scope with assigned variables in memory.
The parser also contains some convenience functions to get, set, and remove
variables from memory.

A parser can be created by:

The parser contains the following functions:

  • Completely clear the parser’s scope.

  • Evaluate an expression. Returns the result of the expression.

  • Retrieve a variable or function from the parser’s scope.

  • Retrieve a map with all defined a variables from the parser’s scope.

  • Remove a variable or function from the parser’s scope.

  • Set a variable or function in the parser’s scope.

The following code shows how to create and use a parser.

Statistics functions #

Function Description
math.mad(a, b, c, …) Compute the median absolute deviation of a matrix or a list with values.
math.max(a, b, c, …) Compute the maximum value of a matrix or a list with values.
math.mean(a, b, c, …) Compute the mean value of matrix or a list with values.
math.median(a, b, c, …) Compute the median of a matrix or a list with values.
math.min(a, b, c, …) Compute the minimum value of a matrix or a list of values.
math.mode(a, b, c, …) Computes the mode of a set of numbers or a list with values(numbers or characters).
math.prod(a, b, c, …) Compute the product of a matrix or a list with values.
math.quantileSeq(A, prob) Compute the prob order quantile of a matrix or a list with values.
math.std(a, b, c, …) Compute the standard deviation of a matrix or a list with values.
math.sum(a, b, c, …) Compute the sum of a matrix or a list with values.
math.variance(a, b, c, …) Compute the variance of a matrix or a list with values.

Uwagi

Zachowanie tej metody jest zgodne ze standardem IEEE 754, sekcja 4.The behavior of this method follows IEEE Standard 754, section 4. Tego rodzaju zaokrąglenie jest czasami nazywane zaokrąglaniem kierunku minus nieskończoność.This kind of rounding is sometimes called rounding toward negative infinity.

Floor(Double)

Zwraca największą wartość całkowitą mniejszą lub równą podanej liczbie zmiennoprzecinkowej podwójnej precyzji.Returns the largest integral value less than or equal to the specified double-precision floating-point number.

d

Double

Liczba zmiennoprzecinkowa podwójnej precyzji.A double-precision floating-point number.

Zwraca

Double

Największa wartość całkowita mniejsza lub równa .The largest integral value less than or equal to . Jeśli jest równe NaN , NegativeInfinity , lub PositiveInfinity , ta wartość jest zwracana.If is equal to NaN, NegativeInfinity, or PositiveInfinity, that value is returned.

Przykłady

Poniższy przykład ilustruje metodę i kontrastuje ją z metodą.The following example illustrates the method and contrasts it with the method.

Uwagi

Zachowanie tej metody jest zgodne ze standardem IEEE 754, sekcja 4.The behavior of this method follows IEEE Standard 754, section 4. Tego rodzaju zaokrąglenie jest czasami nazywane zaokrąglaniem kierunku minus nieskończoność.This kind of rounding is sometimes called rounding toward negative infinity. Innymi słowy, jeśli ma wartość dodatnią, dowolny składnik częściowy zostanie obcięty.In other words, if is positive, any fractional component is truncated. Jeśli jest ujemna, obecność dowolnego komponentu ułamkowego powoduje Zaokrąglenie do mniejszej liczby całkowitej.If is negative, the presence of any fractional component causes it to be rounded to the smaller integer. Operacja tej metody różni się od Ceiling metody, która obsługuje zaokrąglanie w kierunku nieskończoności dodatniej.The operation of this method differs from the Ceiling method, which supports rounding toward positive infinity.

Począwszy od Visual Basic 15,8, wydajność konwersji podwójnej do liczby całkowitej jest zoptymalizowana, jeśli przekazujesz wartość zwróconą przez metodę do którejkolwiek funkcji konwersjicałkowitej lub jeśli wartość podwójna zwracana przez jest automatycznie konwertowana na liczbę całkowitą z opcją Strict ustawiona na off.Starting with Visual Basic 15.8, the performance of Double-to-integer conversion is optimized if you pass the value returned by the method to the any of the integral conversion functions, or if the Double value returned by is automatically converted to an integer with Option Strict set to Off. Ta optymalizacja umożliwia szybsze uruchamianie kodu — maksymalnie dwa razy w przypadku kodu, który wykonuje dużą liczbę konwersji na typy całkowite.This optimization allows code to run faster — up to twice as fast for code that does a large number of conversions to integer types. Poniższy przykład ilustruje takie zoptymalizowane konwersje:The following example illustrates such optimized conversions:

Arrays and matrices #

Math.js supports two types of matrices:

  • , a regular JavaScript array. A multi dimensional array can be created
    by nesting arrays.
  • , a matrix implementation by math.js. A is an object wrapped
    around a regular JavaScript , providing utility functions for easy
    matrix manipulation such as , , , , and more.

In most cases, the type of matrix output from functions is determined by the
function input: An as input will return an , a as input
will return a . In case of mixed input, a is returned.
For functions where the type of output cannot be determined from the
input, the output is determined by the configuration option ,
which can be a string (default) or .

Set functions #

Function Description
math.setCartesian(set1, set2) Create the cartesian product of two (multi)sets.
math.setDifference(set1, set2) Create the difference of two (multi)sets: every element of set1, that is not the element of set2.
math.setDistinct(set) Collect the distinct elements of a multiset.
math.setIntersect(set1, set2) Create the intersection of two (multi)sets.
math.setIsSubset(set1, set2) Check whether a (multi)set is a subset of another (multi)set.
math.setMultiplicity(element, set) Count the multiplicity of an element in a multiset.
math.setPowerset(set) Create the powerset of a (multi)set.
math.setSize(set) Count the number of elements of a (multi)set.
math.setSymDifference(set1, set2) Create the symmetric difference of two (multi)sets.
math.setUnion(set1, set2) Create the union of two (multi)sets.

Matrix functions #

Function Description
math.apply(A, dim, callback) Apply a function that maps an array to a scalar along a given axis of a matrix or array.
math.column(value, index) Return a column from a Matrix.
math.concat(a, b, c, … ) Concatenate two or more matrices.
math.cross(x, y) Calculate the cross product for two vectors in three dimensional space.
math.ctranspose(x) Transpose and complex conjugate a matrix.
math.det(x) Calculate the determinant of a matrix.
math.diag(X) Create a diagonal matrix or retrieve the diagonal of a matrix When is a vector, a matrix with vector on the diagonal will be returned.
math.diff(arr) Create a new matrix or array of the difference between elements of the given array The optional dim parameter lets you specify the dimension to evaluate the difference of If no dimension parameter is passed it is assumed as dimension 0 Dimension is zero-based in javascript and one-based in the parser and can be a number or bignumber Arrays must be ‘rectangular’ meaning arrays like If something is passed as a matrix it will be returned as a matrix but other than that all matrices are converted to arrays.
math.dot(x, y) Calculate the dot product of two vectors.
math.eigs(x) Compute eigenvalue and eigenvector of a real symmetric matrix.
math.expm(x) Compute the matrix exponential, expm(A) = e^A.
math.filter(x, test) Filter the items in an array or one dimensional matrix.
math.flatten(x) Flatten a multi dimensional matrix into a single dimensional matrix.
math.forEach(x, callback) Iterate over all elements of a matrix/array, and executes the given callback function.
math.getMatrixDataType(x) Find the data type of all elements in a matrix or array, for example ‘number’ if all items are a number and ‘Complex’ if all values are complex numbers.
math.identity(n) Create a 2-dimensional identity matrix with size m x n or n x n.
math.inv(x) Calculate the inverse of a square matrix.
math.kron(x, y) Calculates the kronecker product of 2 matrices or vectors.
math.map(x, callback) Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array.
math.ones(m, n, p, …) Create a matrix filled with ones.
math.partitionSelect(x, k) Partition-based selection of an array or 1D matrix.
math.range(start, end ) Create an array from a range.
math.reshape(x, sizes) Reshape a multi dimensional array to fit the specified dimensions.
math.resize(x, size ) Resize a matrix.
math.rotate(w, theta) Rotate a vector of size 1×2 counter-clockwise by a given angle Rotate a vector of size 1×3 counter-clockwise by a given angle around the given axis.
math.rotationMatrix(theta) Create a 2-dimensional counter-clockwise rotation matrix (2×2) for a given angle (expressed in radians).
math.row(value, index) Return a row from a Matrix.
math.size(x) Calculate the size of a matrix or scalar.
math.sort(x) Sort the items in a matrix.
X = math.sqrtm(A) Calculate the principal square root of a square matrix.
math.squeeze(x) Squeeze a matrix, remove inner and outer singleton dimensions from a matrix.
math.subset(x, index ) Get or set a subset of a matrix or string.
math.trace(x) Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix.
math.transpose(x) Transpose a matrix.
math.zeros(m, n, p, …) Create a matrix filled with zeros.

1 Округление вещественных чисел

Как мы уже разбирали, при присваивании переменной типа вещественного числа оно всегда округляется вниз до целого — его дробная часть просто отбрасывается.

А ведь легко можно представить ситуацию, когда дробное число нужно округлить просто до ближайшего целого или вообще вверх. Что делать в этой ситуации?

Для этого и для многих похожих случаев в Java есть класс , у которого есть методы , , .

Метод

Метод округляет число до ближайшего целого:

Но, как говорится, есть нюанс: результат работы этого метода — целочисленный тип (не ). Вещественные числа ведь могут быть очень большими, поэтому разработчики Java решили использовать самый большой целочисленный тип, который есть в Java — .

Поэтому чтобы присвоить результат в переменную типа , программист должен явно указать компилятору, что он согласен с возможной потерей данных (вдруг число не поместится в тип ).

Примеры:

Команда Результат

Метод

Метод округляет число до целого вверх, примеры:

Команда Результат

Метод

Метод округляет число до целого вниз, примеры:

Команда Результат

Хотя, для округления числа до целого вниз, будет проще использовать просто оператор приведения типа — :

Команда Результат

Если вам сложно запомнить эти команды, вам поможет небольшой урок английского:

  • — математика
  • — круг/округлять
  • — потолок
  • — пол

Арифметические функции в Python

Арифметические функции используются для представления чисел в различных формах и осуществления над ними математических операций. Далее представлен перечень самых популярных арифметических функций:

  • : округление определенного числа вверх;
  • : возвращает модуль (абсолютное значение) указанного числа;
  • : округление определенного числа вниз;
  • : получение наибольшего общего делителя чисел и ;
  • : возвращает сумму всех элементов итерируемого объекта;
  • : возвращает (e^x)-1;
  • : когда значение слишком мало, вычисление может привести к значительной потери в точности. может вернуть вывод с полной точностью.

В следующем примере показано использование перечисленных выше функций:

Python

import math

num = -4.28
a = 14
b = 8

num_list =
x = 1e-4 # Малое значение x

print(‘Число:’, num)
print(‘Округление числа вниз:’, math.floor(num))
print(‘Округление числа вверх:’, math.ceil(num))
print(‘Модуль числа:’, math.fabs(num))
print(‘Наибольший общий делитель a и b: ‘ + str(math.gcd(a, b)))
print(‘Сумма элементов списка: ‘ + str(math.fsum(num_list)))
print(‘e^x (при использовании функции exp()) равно:’, math.exp(x)-1)
print(‘e^x (при использовании функции expml()) равно:’, math.expm1(x))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

importmath

num=-4.28

a=14

b=8

num_list=10,8.25,75,7.04,-86.23,-6.43,8.4

x=1e-4# Малое значение x

print(‘Число:’,num)

print(‘Округление числа вниз:’,math.floor(num))

print(‘Округление числа вверх:’,math.ceil(num))

print(‘Модуль числа:’,math.fabs(num))

print(‘Наибольший общий делитель a и b: ‘+str(math.gcd(a,b)))

print(‘Сумма элементов списка: ‘+str(math.fsum(num_list)))

print(‘e^x (при использовании функции exp()) равно:’,math.exp(x)-1)

print(‘e^x (при использовании функции expml()) равно:’,math.expm1(x))

Вывод

Python

Число: -4.28
Округление числа вниз: -5
Округление числа вверх: -4
Модуль числа: 4.28
Наибольший общий делитель a и b: 2
Сумма элементов списка: 16.029999999999998
e^x (при использовании функции exp()) равно: 0.0001000050001667141
e^x (при использовании функции expml()) равно: 0.00010000500016667084

1
2
3
4
5
6
7
8

Число-4.28

Округлениечиславниз-5

Округлениечиславверх-4

Модульчисла4.28

Наибольшийобщийделительaиb2

Суммаэлементовсписка16.029999999999998

e^x(прииспользованиифункцииexp())равно0.0001000050001667141

e^x(прииспользованиифункцииexpml())равно0.00010000500016667084

К числу других математических функций относятся:

  • : принимает два вещественных аргумента, возводит первый аргумент в степень, значением которой является второй аргумент, после чего возвращает результат. К примеру, эквивалентно выражению ;
  • : возвращает квадратный корень определенного числа.

Примеры данных методов представлены ниже:

Возведение в степень

Python

math.pow(3, 4)

1 math.pow(3,4)

Вывод

Shell

81.0

1 81.0

Квадратный корень

Python

math.sqrt(81)

1 math.sqrt(81)

Вывод

Shell

9.0

1 9.0

Объект Math. Математические операции

Последнее обновление: 1.11.2015

Объект Math предоставляет ряд математических функций, которые можно использовать при вычислениях. Рассмотрим основные математические функции.

abs()

Функция возвращает абсолютное значение числа:

var x = -25;
document.write(Math.abs(x)); // 25
var y = 34;
document.write(Math.abs(y)); // 34

min() и max()

Функции и возвращают соответственно минимальное и максимальное значение из набора чисел:

var max = Math.max(19, 45); // 45
var min = Math.min(33, 24); // 24

Эти функции необязательно должны принимать два числа, в них можно передавать и большее количество чисел:

var max = Math.max(1, 2, 3, -9, 46, -23); // 46

ceil()

Функция округляет число до следующего наибольшего целого числа:

var x = Math.ceil(9.2); // 10
var y = Math.ceil(-5.9); // -5

Выражение возвращает число 10, так как число 10 следующее наибольшее целое число после 9.2. И также
выражение возвращает -5, потому что число -5 следующее наибольшее целое после -5.9

floor()

Функция округляет число до следующего наименьшего целого числа:

var x = Math.floor(9.2); // 9
var y = Math.floor(-5.9); // -6

round()

Функция округляет число до следующего наименьшего целого числа, если его десятичная часть меньше 0.5. Если же десятичная
часть равна или больше 0.5, то округление идет до ближайшего наибольшего целого числа:

var x = Math.round(5.5); // 6
var y = Math.round(5.4); // 5
var z = Math.round(-5.4); // -5
var n = Math.round(-5.5); // -5
var m = Math.round(-5.6); // -6
console.log(x);
console.log(y);
console.log(z);
console.log(n);

Функция возвращает случайное число с плавающей точкой их диапазона от 0 до 1:

var x = Math.random();

Функция возвращает число в определенной степени. Например, возведем число 2 в степень 3:

var x = Math.pow(2, 3); // 8

sqrt()

Функция возвращает квадратный корень числа:

var x = Math.sqrt(121); // 11
var y = Math.sqrt(9); // 3
var z = Math.sqrt(20); // 4.47213595499958

Функция возвращает натуральный логарифм числа:

var x = Math.log(1); // 0
var z = Math.log(10); // 2.302585092994046

Тригонометрические функции

Целый ряд функций представляют тригонометрические функции: (вычисляет синус угла),
(вычисляет косинус угла), (вычисляет тангенс угла). В качестве значения они приимают значение в радианах.

var x = Math.sin(Math.PI/2); // 1
var y = Math.cos(0); // 1
var z = Math.tan(Math.PI/4); // 0.9999999999999999
var s = Math.sin(Math.PI/4); // 0.7071067811865476
var c = Math.cos(Math.PI/4); // 0.7071067811865476
console.log(x, y, z, s, c);

Функция вычисляет арксинус числа, — арккосинус, а — арктангенс числа:

var x = Math.asin(0.9); // 1.1197695149986342
var y = Math.acos(1); // 1
var z = Math.atan(1); // 0.7853981633974483

Константы

Кроме методов объект Math также определяет набор встроенных констант, которые можно использовать в различных вычислениях:

  • (число PI): 3.141592653589793

  • (квадратный корень из двух): 1.4142135623730951

  • (половина от квадратного корня из двух): 0.7071067811865476

  • (число e или число Эйлера): 2.718281828459045

  • (натуральный логарифм числа 2): 0.6931471805599453

  • (натуральный логарифм числа 10): 2.302585092994046

  • (двоичный логарифм числа e): 1.4426950408889634

  • (десятичный логарифм числа e): 0.4342944819032518

Используем константы в вычислениях:

var x = Math.log(Math.E); // 1
var z = Math.tan(Math.PI/4); // 0.9999999999999999

НазадВперед

Trigonometry functions #

Function Description
math.acos(x) Calculate the inverse cosine of a value.
math.acosh(x) Calculate the hyperbolic arccos of a value, defined as .
math.acot(x) Calculate the inverse cotangent of a value, defined as .
math.acoth(x) Calculate the hyperbolic arccotangent of a value, defined as .
math.acsc(x) Calculate the inverse cosecant of a value, defined as .
math.acsch(x) Calculate the hyperbolic arccosecant of a value, defined as .
math.asec(x) Calculate the inverse secant of a value.
math.asech(x) Calculate the hyperbolic arcsecant of a value, defined as .
math.asin(x) Calculate the inverse sine of a value.
math.asinh(x) Calculate the hyperbolic arcsine of a value, defined as .
math.atan(x) Calculate the inverse tangent of a value.
math.atan2(y, x) Calculate the inverse tangent function with two arguments, y/x.
math.atanh(x) Calculate the hyperbolic arctangent of a value, defined as .
math.cos(x) Calculate the cosine of a value.
math.cosh(x) Calculate the hyperbolic cosine of a value, defined as .
math.cot(x) Calculate the cotangent of a value.
math.coth(x) Calculate the hyperbolic cotangent of a value, defined as .
math.csc(x) Calculate the cosecant of a value, defined as .
math.csch(x) Calculate the hyperbolic cosecant of a value, defined as .
math.sec(x) Calculate the secant of a value, defined as .
math.sech(x) Calculate the hyperbolic secant of a value, defined as .
math.sin(x) Calculate the sine of a value.
math.sinh(x) Calculate the hyperbolic sine of a value, defined as .
math.tan(x) Calculate the tangent of a value.
math.tanh(x) Calculate the hyperbolic tangent of a value, defined as .
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector