Синус в питоне как написать

от admin

Модуль math . Тригонометрические функции

Все тригонометрические функции оперируют радианами. Зависимость между радианами и градусами определяется по формуле:

1 радиан = 180°/π = 57.2958°

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

Например. Задан угол, имеющий n градусов. Найти арккосинус этого угла. В этом случае формула вычисления результата будет следующей:

Чтобы получить более точное значение результата, в программе можно использовать константу math.pi , которая определяет число π. В этом случае текст программы будет иметь следующий вид

2. Средства языка Python для конвертирования из градусов в радианы и наоборот. Функции math.degrees(x) и math.radians(x)

В языке Python существуют функции преобразования из градусов в радианы и, наоборот, из радиан в градусы.

Функция math.degrees(x) конвертирует значение параметра x из радиан в градусы.
Функция math.radians(x) конвертирует значение параметра x из градусов в радианы.

Пример.

3. Ограничения на использование тригонометрических функций

При использовании тригонометрических функций следует учитывать соответствующие ограничения, которые следуют из самой сущности этих функций. Например, не существует арксинуса из числа, которое больше 1.
Если при вызове функции задать неправильный аргумент, то интерпретатор выдаст соответствующее сообщение об ошибке

4. Функция math.acos(x) . Арккосинус угла

Функция acos(x) возвращает арккосинус угла x . Аргумент x задается в радианах и может быть как целым числом, так и вещественным числом.

Пример.

Результат работы программы

5. Функция math.asin(x) . Арксинус

Функция math.asin(x) вычисляет арксинус угла от аргумента x . Значение аргумента x задается в радианах.

Пример.

6. Функция math.atan(x) . Арктангенс

Функция math.atan(x) возвращает арктангенс аргумента x, значение которого задается в радианах. При использовании функции важно помнить допустимые значения x , которые можно задавать при вычислении арктангенса.

Пример.

7. Функция math.atan2(x, y) . Арктангенс от x/y

Функция math.atan2(x, y) вычисляет арктангенс угла от деления x на y . Функция возвращает результат от —π до π. Аргументы x , y определяют координаты точки, через которую проходит отрезок от начала координат. В отличие от функции atan(x) , данная функция правильно вычисляет квадрант, влияющий на знак результата.

Пример.

8. Функция math.cos(x). Косинус угла

Функция math.cos(x) вычисляет косинус угла для аргумента x . Значение аргумента x задается в радианах.

Пример.

9. Функция math.sin(x)

Функция math.sin(x) возвращает синус угла от аргумента x , заданного в радианах.

Пример.

10. Функция math.hypot(x, y) . Евклидовая норма (Euclidean norm)

Функция возвращает Евклидовую норму, которая равна длине вектора от начала координат до точки x , y и определяется по формуле

math — Mathematical functions¶

This module provides access to the mathematical functions defined by the C standard.

These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for complex numbers. The distinction between functions which support complex numbers and those which don’t is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Receiving an exception instead of a complex result allows earlier detection of the unexpected complex number used as a parameter, so that the programmer can determine how and why it was generated in the first place.

The following functions are provided by this module. Except when explicitly noted otherwise, all return values are floats.

Number-theoretic and representation functions¶

Return the ceiling of x, the smallest integer greater than or equal to x. If x is not a float, delegates to x.__ceil__ , which should return an Integral value.

Return the number of ways to choose k items from n items without repetition and without order.

Evaluates to n! / (k! * (n — k)!) when k <= n and evaluates to zero when k > n .

Also called the binomial coefficient because it is equivalent to the coefficient of k-th term in polynomial expansion of (1 + x)ⁿ .

Raises TypeError if either of the arguments are not integers. Raises ValueError if either of the arguments are negative.

New in version 3.8.

Return a float with the magnitude (absolute value) of x but the sign of y. On platforms that support signed zeros, copysign(1.0, -0.0) returns -1.0.

Return the absolute value of x.

math. factorial ( n ) ¶

Return n factorial as an integer. Raises ValueError if n is not integral or is negative.

Deprecated since version 3.9: Accepting floats with integral values (like 5.0 ) is deprecated.

Return the floor of x, the largest integer less than or equal to x. If x is not a float, delegates to x.__floor__ , which should return an Integral value.

Return fmod(x, y) , as defined by the platform C library. Note that the Python expression x % y may not return the same result. The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x — n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y) . Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100 , but the result of Python’s -1e-100 % 1e100 is 1e100-1e-100 , which cannot be represented exactly as a float, and rounds to the surprising 1e100 . For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.

Return the mantissa and exponent of x as the pair (m, e) . m is a float and e is an integer such that x == m * 2**e exactly. If x is zero, returns (0.0, 0) , otherwise 0.5 <= abs(m) < 1 . This is used to “pick apart” the internal representation of a float in a portable way.

math. fsum ( iterable ) ¶

Return an accurate floating point sum of values in the iterable. Avoids loss of precision by tracking multiple intermediate partial sums:

The algorithm’s accuracy depends on IEEE-754 arithmetic guarantees and the typical case where the rounding mode is half-even. On some non-Windows builds, the underlying C library uses extended precision addition and may occasionally double-round an intermediate sum causing it to be off in its least significant bit.

For further discussion and two alternative approaches, see the ASPN cookbook recipes for accurate floating point summation.

math. gcd ( * integers ) ¶

Return the greatest common divisor of the specified integer arguments. If any of the arguments is nonzero, then the returned value is the largest positive integer that is a divisor of all arguments. If all arguments are zero, then the returned value is 0 . gcd() without arguments returns 0 .

New in version 3.5.

Changed in version 3.9: Added support for an arbitrary number of arguments. Formerly, only two arguments were supported.

Return True if the values a and b are close to each other and False otherwise.

Whether or not two values are considered close is determined according to given absolute and relative tolerances.

rel_tol is the relative tolerance – it is the maximum allowed difference between a and b, relative to the larger absolute value of a or b. For example, to set a tolerance of 5%, pass rel_tol=0.05 . The default tolerance is 1e-09 , which assures that the two values are the same within about 9 decimal digits. rel_tol must be greater than zero.

abs_tol is the minimum absolute tolerance – useful for comparisons near zero. abs_tol must be at least zero.

If no errors occur, the result will be: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) .

The IEEE 754 special values of NaN , inf , and -inf will be handled according to IEEE rules. Specifically, NaN is not considered close to any other value, including NaN . inf and -inf are only considered close to themselves.

New in version 3.5.

PEP 485 – A function for testing approximate equality

Return True if x is neither an infinity nor a NaN, and False otherwise. (Note that 0.0 is considered finite.)

New in version 3.2.

Return True if x is a positive or negative infinity, and False otherwise.

Return True if x is a NaN (not a number), and False otherwise.

Return the integer square root of the nonnegative integer n. This is the floor of the exact square root of n, or equivalently the greatest integer a such that a² ≤ n.

For some applications, it may be more convenient to have the least integer a such that na², or in other words the ceiling of the exact square root of n. For positive n, this can be computed using a = 1 + isqrt(n — 1) .

New in version 3.8.

Return the least common multiple of the specified integer arguments. If all arguments are nonzero, then the returned value is the smallest positive integer that is a multiple of all arguments. If any of the arguments is zero, then the returned value is 0 . lcm() without arguments returns 1 .

New in version 3.9.

Return x * (2**i) . This is essentially the inverse of function frexp() .

Return the fractional and integer parts of x. Both results carry the sign of x and are floats.

Return the next floating-point value after x towards y.

math.nextafter(x, math.inf) goes up: towards positive infinity.

math.nextafter(x, -math.inf) goes down: towards minus infinity.

math.nextafter(x, 0.0) goes towards zero.

math.nextafter(x, math.copysign(math.inf, x)) goes away from zero.

New in version 3.9.

Return the number of ways to choose k items from n items without repetition and with order.

Evaluates to n! / (n — k)! when k <= n and evaluates to zero when k > n .

If k is not specified or is None, then k defaults to n and the function returns n! .

Raises TypeError if either of the arguments are not integers. Raises ValueError if either of the arguments are negative.

New in version 3.8.

Calculate the product of all the elements in the input iterable. The default start value for the product is 1 .

When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types.

New in version 3.8.

Return the IEEE 754-style remainder of x with respect to y. For finite x and finite nonzero y, this is the difference x — n*y , where n is the closest integer to the exact value of the quotient x / y . If x / y is exactly halfway between two consecutive integers, the nearest even integer is used for n . The remainder r = remainder(x, y) thus always satisfies abs(r) <= 0.5 * abs(y) .

Special cases follow IEEE 754: in particular, remainder(x, math.inf) is x for any finite x, and remainder(x, 0) and remainder(math.inf, x) raise ValueError for any non-NaN x. If the result of the remainder operation is zero, that zero will have the same sign as x.

On platforms using IEEE 754 binary floating-point, the result of this operation is always exactly representable: no rounding error is introduced.

New in version 3.7.

Return x with the fractional part removed, leaving the integer part. This rounds toward 0: trunc() is equivalent to floor() for positive x, and equivalent to ceil() for negative x. If x is not a float, delegates to x.__trunc__ , which should return an Integral value.

Return the value of the least significant bit of the float x:

If x is a NaN (not a number), return x.

If x is negative, return ulp(-x) .

If x is a positive infinity, return x.

If x is equal to zero, return the smallest positive denormalized representable float (smaller than the minimum positive normalized float, sys.float_info.min ).

If x is equal to the largest positive representable float, return the value of the least significant bit of x, such that the first float smaller than x is x — ulp(x) .

Otherwise (x is a positive finite number), return the value of the least significant bit of x, such that the first float bigger than x is x + ulp(x) .

ULP stands for “Unit in the Last Place”.

New in version 3.9.

Note that frexp() and modf() have a different call/return pattern than their C equivalents: they take a single argument and return a pair of values, rather than returning their second return value through an ‘output parameter’ (there is no such thing in Python).

For the ceil() , floor() , and modf() functions, note that all floating-point numbers of sufficiently large magnitude are exact integers. Python floats typically carry no more than 53 bits of precision (the same as the platform C double type), in which case any float x with abs(x) >= 2**52 necessarily has no fractional bits.

Power and logarithmic functions¶

Return the cube root of x.

New in version 3.11.

Return e raised to the power x, where e = 2.718281… is the base of natural logarithms. This is usually more accurate than math.e ** x or pow(math.e, x) .

Return 2 raised to the power x.

New in version 3.11.

Return e raised to the power x, minus 1. Here e is the base of natural logarithms. For small floats x, the subtraction in exp(x) — 1 can result in a significant loss of precision; the expm1() function provides a way to compute this quantity to full precision:

New in version 3.2.

With one argument, return the natural logarithm of x (to base e).

With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base) .

Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.

Return the base-2 logarithm of x. This is usually more accurate than log(x, 2) .

New in version 3.3.

int.bit_length() returns the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros.

Return the base-10 logarithm of x. This is usually more accurate than log(x, 10) .

Return x raised to the power y . Exceptional cases follow the IEEE 754 standard as far as possible. In particular, pow(1.0, x) and pow(x, 0.0) always return 1.0 , even when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow(x, y) is undefined, and raises ValueError .

Unlike the built-in ** operator, math.pow() converts both its arguments to type float . Use ** or the built-in pow() function for computing exact integer powers.

Changed in version 3.11: The special cases pow(0.0, -inf) and pow(-0.0, -inf) were changed to return inf instead of raising ValueError , for consistency with IEEE 754.

Return the square root of x.

Trigonometric functions¶

Return the arc cosine of x, in radians. The result is between 0 and pi .

Return the arc sine of x, in radians. The result is between -pi/2 and pi/2 .

Return the arc tangent of x, in radians. The result is between -pi/2 and pi/2 .

Return atan(y / x) , in radians. The result is between -pi and pi . The vector in the plane from the origin to point (x, y) makes this angle with the positive X axis. The point of atan2() is that the signs of both inputs are known to it, so it can compute the correct quadrant for the angle. For example, atan(1) and atan2(1, 1) are both pi/4 , but atan2(-1, -1) is -3*pi/4 .

Return the cosine of x radians.

Return the Euclidean distance between two points p and q, each given as a sequence (or iterable) of coordinates. The two points must have the same dimension.

Roughly equivalent to:

New in version 3.8.

Return the Euclidean norm, sqrt(sum(x**2 for x in coordinates)) . This is the length of the vector from the origin to the point given by the coordinates.

For a two dimensional point (x, y) , this is equivalent to computing the hypotenuse of a right triangle using the Pythagorean theorem, sqrt(x*x + y*y) .

Changed in version 3.8: Added support for n-dimensional points. Formerly, only the two dimensional case was supported.

Changed in version 3.10: Improved the algorithm’s accuracy so that the maximum error is under 1 ulp (unit in the last place). More typically, the result is almost always correctly rounded to within 1/2 ulp.

Return the sine of x radians.

Читать:
Imgburn как сделать русский язык

Return the tangent of x radians.

Angular conversion¶

Convert angle x from radians to degrees.

Convert angle x from degrees to radians.

Hyperbolic functions¶

Hyperbolic functions are analogs of trigonometric functions that are based on hyperbolas instead of circles.

Return the inverse hyperbolic cosine of x.

Return the inverse hyperbolic sine of x.

Return the inverse hyperbolic tangent of x.

Return the hyperbolic cosine of x.

Return the hyperbolic sine of x.

Return the hyperbolic tangent of x.

Special functions¶

The erf() function can be used to compute traditional statistical functions such as the cumulative standard normal distribution:

New in version 3.2.

Return the complementary error function at x. The complementary error function is defined as 1.0 — erf(x) . It is used for large values of x where a subtraction from one would cause a loss of significance.

New in version 3.2.

New in version 3.2.

Return the natural logarithm of the absolute value of the Gamma function at x.

New in version 3.2.

Constants¶

The mathematical constant π = 3.141592…, to available precision.

The mathematical constant e = 2.718281…, to available precision.

The mathematical constant τ = 6.283185…, to available precision. Tau is a circle constant equal to 2π, the ratio of a circle’s circumference to its radius. To learn more about Tau, check out Vi Hart’s video Pi is (still) Wrong, and start celebrating Tau day by eating twice as much pie!

New in version 3.6.

A floating-point positive infinity. (For negative infinity, use -math.inf .) Equivalent to the output of float(‘inf’) .

New in version 3.5.

A floating-point “not a number” (NaN) value. Equivalent to the output of float(‘nan’) . Due to the requirements of the IEEE-754 standard, math.nan and float(‘nan’) are not considered to equal to any other numeric value, including themselves. To check whether a number is a NaN, use the isnan() function to test for NaNs instead of is or == . Example:

Changed in version 3.11: It is now always available.

New in version 3.5.

CPython implementation detail: The math module consists mostly of thin wrappers around the platform C math library functions. Behavior in exceptional cases follows Annex F of the C99 standard where appropriate. The current implementation will raise ValueError for invalid operations like sqrt(-1.0) or log(0.0) (where C99 Annex F recommends signaling invalid operation or divide-by-zero), and OverflowError for results that overflow (for example, exp(1000.0) ). A NaN will not be returned from any of the functions above unless one or more of the input arguments was a NaN; in that case, most functions will return a NaN, but (again following C99 Annex F) there are some exceptions to this rule, for example pow(float(‘nan’), 0.0) or hypot(float(‘nan’), float(‘inf’)) .

Note that Python makes no effort to distinguish signaling NaNs from quiet NaNs, and behavior for signaling NaNs remains unspecified. Typical behavior is to treat all NaNs as though they were quiet.

# Math Module

In addition to the built-in round function, the math module provides the floor , ceil , and trunc functions.

floor , ceil , trunc , and round always return a float .

round always breaks ties away from zero.

floor , ceil , and trunc always return an Integral value, while round returns an Integral value if called with one argument.

round breaks ties towards the nearest even number. This corrects the bias towards larger numbers when performing a large number of calculations.

# Warning!

As with any floating-point representation, some fractions cannot be represented exactly. This can lead to some unexpected rounding behavior.

# Warning about the floor, trunc, and integer division of negative numbers

Python (and C++ and Java) round away from zero for negative numbers. Consider:

# Trigonometry

# Calculating the length of the hypotenuse

# Converting degrees to/from radians

All math functions expect radians so you need to convert degrees to radians:

All results of the inverse trigonometic functions return the result in radians, so you may need to convert it back to degrees:

# Sine, cosine, tangent and inverse functions

Apart from the math.atan there is also a two-argument math.atan2 function, which computes the correct quadrant and avoids pitfalls of division by zero:

# Hyperbolic sine, cosine and tangent

# Logarithms

math.log(x) gives the natural (base e ) logarithm of x .

math.log can lose precision with numbers close to 1, due to the limitations of floating-point numbers. In order to accurately calculate logs close to 1, use math.log1p , which evaluates the natural logarithm of 1 plus the argument:

math.log10 can be used for logs base 10:

When used with two arguments, math.log(x, base) gives the logarithm of x in the given base (i.e. log(x) / log(base) .

# Constants

math modules includes two commonly used mathematical constants.

  • math.pi — The mathematical constant pi
  • math.e — The mathematical constant e (base of natural logarithm)

Python 3.5 and higher have constants for infinity and NaN ("not a number"). The older syntax of passing a string to float() still works.

# Infinity and NaN ("not a number")

In all versions of Python, we can represent infinity and NaN ("not a number") as follows:

In Python 3.5 and higher, we can also use the defined constants math.inf and math.nan :

The string representations display as inf and -inf and nan :

We can test for either positive or negative infinity with the isinf method:

We can test specifically for positive infinity or for negative infinity by direct comparison:

Python 3.2 and higher also allows checking for finiteness:

Comparison operators work as expected for positive and negative infinity:

But if an arithmetic expression produces a value larger than the maximum that can be represented as a float , it will become infinity:

However division by zero does not give a result of infinity (or negative infinity where appropriate), rather it raises a ZeroDivisionError exception.

Arithmetic operations on infinity just give infinite results, or sometimes NaN:

NaN is never equal to anything, not even itself. We can test for it is with the isnan method:

NaN always compares as "not equal", but never less than or greater than:

Arithmetic operations on NaN always give NaN. This includes multiplication by -1: there is no "negative NaN".

There is one subtle difference between the old float versions of NaN and infinity and the Python 3.5+ math library constants:

# Pow for faster exponentiation

Using the timeit module from the command line:

The built-in ** operator often comes in handy, but if performance is of the essence, use math.pow. Be sure to note, however, that pow returns floats, even if the arguments are integers:

# Copying signs

In Python 2.6 and higher, math.copysign(x, y) returns x with the sign of y . The returned value is always a float .

# Imaginary Numbers

Imaginary numbers in Python are represented by a "j" or "J" trailing the target number.

# Complex numbers and the cmath module

The cmath module is similar to the math module, but defines functions appropriately for the complex plane.

First of all, complex numbers are a numeric type that is part of the Python language itself rather than being provided by a library class. Thus we don’t need to import cmath for ordinary arithmetic expressions.

Note that we use j (or J ) and not i .

We must use 1j since j would be the name of a variable rather than a numeric literal.

We have the real part and the imag (imaginary) part, as well as the complex conjugate :

The built-in functions abs and complex are also part of the language itself and don’t require any import:

The complex function can take a string, but it can’t have spaces:

But for most functions we do need the module, for instance sqrt :

Naturally the behavior of sqrt is different for complex numbers and real numbers. In non-complex math the square root of a negative number raises an exception:

Functions are provided to convert to and from polar coordinates:

The mathematical field of complex analysis is beyond the scope of this example, but many functions in the complex plane have a "branch cut", usually along the real axis or the imaginary axis. Most modern platforms support "signed zero" as specified in IEEE 754, which provides continuity of those functions on both sides of the branch cut. The following example is from the Python documentation:

The cmath module also provides many functions with direct counterparts from the math module.

In addition to sqrt , there are complex versions of exp , log , log10 , the trigonometric functions and their inverses ( sin , cos , tan , asin , acos , atan ), and the hyperbolic functions and their inverses ( sinh , cosh , tanh , asinh , acosh , atanh ). Note however there is no complex counterpart of math.atan2 , the two-argument form of arctangent.

The constants pi and e are provided. Note these are float and not complex .

The cmath module also provides complex versions of isinf , and (for Python 3.2+) isfinite . See "Infinity and NaN

(opens new window) ". A complex number is considered infinite if either its real part or its imaginary part is infinite.

Likewise, the cmath module provides a complex version of isnan . See "Infinity and NaN

(opens new window) ". A complex number is considered "not a number" if either its real part or its imaginary part is "not a number".

Note there is no cmath counterpart of the math.inf and math.nan constants (from Python 3.5 and higher)

In Python 3.5 and higher, there is an isclose method in both cmath and math modules.

Модуль Math — математика в Python на примерах (Полный Обзор)

Модуль math на примерах

Библиотека Math в Python обеспечивает доступ к некоторым популярным математическим функциям и константам, которые можно использовать в коде для более сложных математических вычислений. Библиотека является встроенным модулем Python, поэтому никакой дополнительной установки через pip делать не нужно. В данной статье будут даны примеры часто используемых функций и констант библиотеки Math в Python.

Содержание статьи

Специальные константы библиотеки math

В библиотеке Math в Python есть две важные математические константы.

Число Пи из библиотеки math

Первой важной математической константой является число Пи (π). Оно обозначает отношение длины окружности к диаметру, его значение 3,141592653589793. Чтобы получить к нему доступ, сначала импортируем библиотеку math следующим образом:

Затем можно получить доступ к константе, вызывая pi :

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

Мы возвели радиус во вторую степень и умножили значение на число Пи, как и следовало сделать в соответствии с формулой πr 2 .

Есть вопросы по Python?

На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

Telegram Чат & Канал

Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

Паблик VK

Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

Число Эйлера из библиотеки math

Число Эйлера (е) является основанием натурального логарифма. Оно также является частью библиотеки Math в Python. Получить доступ к числу можно следующим образом:

В следующем примере представлено, как можно использовать вышеуказанную константу:

Экспонента и логарифм библиотеки math

В данном разделе рассмотрим функции библиотеки Math в Python, которые используются для нахождения экспоненты и логарифмов.

Функция экспоненты exp() в Python

Библиотека Math в Python поставляется с функцией exp() , которую можно использовать для вычисления значения е . К примеру, e x — экспонента от х . Значение е равно 2.718281828459045 .

Метод может быть использован со следующим синтаксисом:

Параметр x может быть положительным или отрицательным числом. Если x не число, метод возвращает ошибку. Рассмотрим пример использования данного метода:

Мы объявили три переменные и присвоили им значения с различными числовыми типами данных. Мы передали значения методу exp() для вычисления их экспоненты.

Мы также можем применить данный метод для встроенных констант, что продемонстрировано ниже:

При передаче не числового значения методу будет сгенерирована ошибка TypeError, как показано далее:

Как видно из примера выше, генерируется ошибка TypeError .

Функция логарифма log() в Python

Функция log() возвращает логарифм определенного числа. Натуральный логарифм вычисляется относительно основания е . В следующем примере показано использование функции логарифма:

В скрипте выше методу передаются числовые значения с различными типами данных. Также рассчитывается натуральный логарифм константы pi . Вывод следующий:

Функция log10() в Python

Метод log10() возвращает логарифм по основанию 10 определенного числа. К примеру:

Функция log2() в Python

Функция log2() возвращает логарифм определенного числа по основанию 2. К примеру:

Функция log(x, y) в Python

Функция log(x, y) возвращает логарифм числа х по основанию y . К примеру:

Функция log1p(x) в Python

Функция log1p(x) рассчитывает логарифм(1+x), как представлено ниже:

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

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

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

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

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

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

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

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

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

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

  • sin(a) : Возвращает синус «а» в радианах;
  • cos(a) : Возвращает косинус «а» в радианах;
  • tan(a) : Возвращает тангенс «а» в радианах;
  • asin(a) : Возвращает инвертированный синус. Аналогичным образом работают «atan» и «acos» ;
  • degrees(a) : Конвертирует угол «a» из радиан в градусы;
  • radians(a) : Конвертирует угол «a» из градусов в радианы.

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

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

Конвертация типов числа в Python

Python может конвертировать начальный тип числа в другой указанный тип. Данный процесс называется «преобразованием». Python может внутренне конвертировать число одного типа в другой, когда в выражении присутствуют смешанные значения. Такой случай продемонстрирован в следующем примере:

В вышеприведенном примере целое число 3 было преобразовано в вещественное число 3.0 с плавающей точкой. Результатом сложения также является число с плавающей точкой (или запятой).

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

Например, чтобы преобразовать целое число в число с плавающей точкой, мы должны вызвать функцию float() , как показано ниже:

Целое число типа integer было преобразовано в вещественное число типа float . float также можно конвертировать в integer следующим образом:

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

Заключение

Библиотека Math предоставляет функции и константы, которые можно использовать для выполнения арифметических и тригонометрических операций в Python. Библиотека изначально встроена в Python, поэтому дополнительную установку перед использованием делать не требуется. Для получения дополнительной информации можете просмотреть официальную документацию.

Являюсь администратором нескольких порталов по обучению языков программирования Python, Golang и Kotlin. В составе небольшой команды единомышленников, мы занимаемся популяризацией языков программирования на русскоязычную аудиторию. Большая часть статей была адаптирована нами на русский язык и распространяется бесплатно.

Похожие статьи