Python mathematical functions

math[править]

Модуль math всегда доступен и обеспечивает доступ к математическим функциям.

Данные функции неприменимы к комплексным числам, для работы с комплексными числами имеются функции с теми же именами в модуле cmath.

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

Теоретико-численные функции и функции представленияправить

  • math.ceil

    Возвращает округленное x как ближайшее целое значение типа float, большее или равное x (округление «вверх»).

    (x)

  • math.copysign

    Возвращает число x со знаком числа y. На платформе, поддерживающей знак нуля copysign(1.0, -0.0) даст -1.0.

    (x, y)

  • math.fabs

    Возвращает абсолютное значение (модуль) числа x. В Python есть встроенная функция abs, но она возвращает модуль числа с тем же типом, что число, здесь же всегда float abs (fabs).

    (x)

  • math.factorial

    Возвращает факториал целого числа x, если x не целое возбуждается ошибка ValueError.

    (x)

  • math.floor

    В противоположность ceil(x) возвращает округленное x как ближайшее целое значение типа float, меньшее или равное x (округление «вниз»).

    (x)

  • math.fmod

    Аналогична функции fmod(x, y) библиотеки C. Отметим, что это не то же самое, что выражение Python x%y. Желательно использовать при работе с объектами float, в то время как x % y больше подходит для int.

    (x, y)

  • math.frexp

    Представляет число в экспоненциальной записи x=m∗2e{\displaystyle x=m*2^{e}} и возвращает мантиссу m (действительное число, модуль которого лежит в интервале от 0.5 до 1) и порядок e (целое число) как пару чисел (m, e). Если x=0, то возвращает (0.0, 0)

    (x)

  • math.fsum

    Возвращает float сумму от числовых элементов итерируемого объекта.

    (iterable)

  • math.isinf

    Проверяет, является ли float объект x плюс или минус бесконечностью, результат соответственно True или False.

    (x)

  • math.isnan

    Проверяет, является ли float объект x объектом NaN (not a number).

    (x)

  • math.ldexp

    Возвращает значение x∗2i{\displaystyle x*2^{i}}, то есть осуществляет действие, обратное функции math.frexp(x).

    (x, i)

  • math.modf

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

    (x)

  • math.trunc

    Возвращает целую часть числа x в виде int объекта.

    (x)

Степенные и логарифмические функцииправить

  • math.exp

    Возвращает ex{\displaystyle e^{x}}.

    (x)

  • math.log

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

    (x)

  • math.log1p

    Возвращает натуральный логарифм от x+1.

    (x)

  • math.log10

    Возвращает десятичный логарифм x.

    (x)

  • math.pow

    Возвращает xy{\displaystyle x^{y}}.

    (x, y)

  • math.sqrt

    Квадратный корень (square root) из x.

    (x)

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

  • math.acos

    Возвращает арккосинус x, в радианах.

    (x)

  • math.asin

    Возвращает арксинус x, в радианах.

    (x)

  • math.atan

    Возвращает арктангенс x, в радианах.

    (x)

  • math.atan2

    Возвращает atan(y/x), в радианах. Результат лежит в интервале . Вектор, конец, которого задается точкой (x, y) образует угол с положительным направлением оси x. Поэтому эта функция имеет более общее назначение, чем предыдущая. Например и atan(1), и atan2(1, 1) дадут в результате pi/4, но atan2(-1, -1) это уже -3*pi/4.

    (y, x)

  • math.cos

    Возвращает косинус x, где x выражен в радианах.

    (x)

  • math.hyp

    Возвращает евклидову норму, то есть sqrt(x**2+y**2). Удобно для вычисления гипотенузы (hyp) и длины вектора.

    (x, y)

  • math.sin

    Возвращает синус x, где x выражен в радианах.

    (x)

  • math.tan

    Возвращает тангенс x, где x выражен в радианах.

    (x)

Радианы в градусы и наоборотправить

  • math.degrees

    Конвертирует значение угла x из радиан в градусы.

    (x)

  • math.radians

    Конвертирует значение угла x из градусов в радианы.

    (x)

Гиперболические функцииправить

Смысл ясен из названий и соответствует стандартным обозначениям англоязычной литературы:

  • math.acosh(x)
  • math.asinh(x)
  • math.atanh(x)
  • math.cosh(x)
  • math.sinh(x)
  • math.tanh(x)

Python NumPy

NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random
Random Intro
Data Distribution
Random Permutation
Seaborn Module
Normal Distribution
Binomial Distribution
Poisson Distribution
Uniform Distribution
Logistic Distribution
Multinomial Distribution
Exponential Distribution
Chi Square Distribution
Rayleigh Distribution
Pareto Distribution
Zipf Distribution

NumPy ufunc
ufunc Intro
ufunc Create Function
ufunc Simple Arithmetic
ufunc Rounding Decimals
ufunc Logs
ufunc Summations
ufunc Products
ufunc Differences
ufunc Finding LCM
ufunc Finding GCD
ufunc Trigonometric
ufunc Hyperbolic
ufunc Set Operations

Python Assignment Operators

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example
= Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c
+= Add AND It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a
-= Subtract AND It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c — a
*= Multiply AND It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a
/= Divide AND It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / a
%= Modulus AND It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a
**= Exponent AND Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a
//= Floor Division It performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a

4 ответа

Да, я считаю, что вы должны импортировать свою функцию в оболочку.

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

Но учтите, что Python предлагает встроенный оператор power:

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

означает, что ваша оболочка python не распознает функцию. Вы, вероятно, забыли импортировать скрипт.

Предполагая, что вы сохранили ваш файл как ( в том же каталоге, где вы запускаете оболочку Python ) >), вы должны использовать:

для функций, определенных внутри, чтобы быть доступными

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

В качестве альтернативы можно ввести : в этом случае вы создаете доступно в пространстве имен как . Будьте осторожны, чтобы не перезаписывать встроенную функцию этим …

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

Блок while должен иметь отступ на один уровень (4 пробела), чтобы обозначить его в блоке def для функции sqrt.

Наличие блоков if /else внутри операторов while означает, что проверка выполняется при каждом прохождении цикла; следовательно, в первый раз, когда ans будет равен только одному, этот тест будет выполнен, ваш вывод будет напечатан и возвращено значение. Нам нужно это изменить. Несколько других ответов дают более простые способы выразить это в python, но, сохраняя максимально возможный код, который вы написали, все, что вам на самом деле нужно сделать, это переместить блок if и блок else из пока блок. Код показан ниже:

Примеры ввода и вывода показаны:
В:

Из:

В:

Из:

РЕДАКТИРОВАТЬ: На мой взгляд, Python — отличный первый язык. Когда я только начинал с него, я обнаружил класс MIT OpenCourseWare очень полезен

Одно очень важное замечание: класс преподается с использованием Python 2.x вместо 3.x, поэтому часть кода не будет работать для вас. Даже если вы не смотрите все видео лекции, задания, которые они дают , имеют разумную трудность, и задания по чтению ссылаются на некоторые превосходные учебные материалы по питону

Класс Udacity CS101 также предлагает хорошее, направленное введение в программирование на Python ( и также использует Python 2.x ), но я проработал там только половину заданий. Однако я все же рекомендую взглянуть на него.

Functions in Python Math Module

Here is the list of all the functions and attributes defined in module with a brief explanation of what they do.

List of Functions in Python Math Module
Function Description
ceil(x) Returns the smallest integer greater than or equal to x.
copysign(x, y) Returns x with the sign of y
fabs(x) Returns the absolute value of x
factorial(x) Returns the factorial of x
floor(x) Returns the largest integer less than or equal to x
fmod(x, y) Returns the remainder when x is divided by y
frexp(x) Returns the mantissa and exponent of x as the pair (m, e)
fsum(iterable) Returns an accurate floating point sum of values in the iterable
isfinite(x) Returns True if x is neither an infinity nor a NaN (Not a Number)
isinf(x) Returns True if x is a positive or negative infinity
isnan(x) Returns True if x is a NaN
ldexp(x, i) Returns x * (2**i)
modf(x) Returns the fractional and integer parts of x
trunc(x) Returns the truncated integer value of x
exp(x) Returns e**x
expm1(x) Returns e**x — 1
log(x) Returns the logarithm of x to the base (defaults to e)
log1p(x) Returns the natural logarithm of 1+x
log2(x) Returns the base-2 logarithm of x
log10(x) Returns the base-10 logarithm of x
pow(x, y) Returns x raised to the power y
sqrt(x) Returns the square root of x
acos(x) Returns the arc cosine of x
asin(x) Returns the arc sine of x
atan(x) Returns the arc tangent of x
atan2(y, x) Returns atan(y / x)
cos(x) Returns the cosine of x
hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)
sin(x) Returns the sine of x
tan(x) Returns the tangent of x
degrees(x) Converts angle x from radians to degrees
radians(x) Converts angle x from degrees to radians
acosh(x) Returns the inverse hyperbolic cosine of x
asinh(x) Returns the inverse hyperbolic sine of x
atanh(x) Returns the inverse hyperbolic tangent of x
cosh(x) Returns the hyperbolic cosine of x
sinh(x) Returns the hyperbolic cosine of x
tanh(x) Returns the hyperbolic tangent of x
erf(x) Returns the error function at x
erfc(x) Returns the complementary error function at x
gamma(x) Returns the Gamma function at x
lgamma(x) Returns the natural logarithm of the absolute value of the Gamma function at x
pi Mathematical constant, the ratio of circumference of a circle to it’s diameter (3.14159…)
e mathematical constant e (2.71828…)

Visit this page to learn about all the mathematical functions defined in Python 3.

Python NumPy

NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random
Random Intro
Data Distribution
Random Permutation
Seaborn Module
Normal Distribution
Binomial Distribution
Poisson Distribution
Uniform Distribution
Logistic Distribution
Multinomial Distribution
Exponential Distribution
Chi Square Distribution
Rayleigh Distribution
Pareto Distribution
Zipf Distribution

NumPy ufunc
ufunc Intro
ufunc Create Function
ufunc Simple Arithmetic
ufunc Rounding Decimals
ufunc Logs
ufunc Summations
ufunc Products
ufunc Differences
ufunc Finding LCM
ufunc Finding GCD
ufunc Trigonometric
ufunc Hyperbolic
ufunc Set Operations

cmath vs math#

A complex number is a combination of a real number and an imaginary number. It has the formula of a + bi, where a is the real number and bi is the imaginary number. Real and imaginary numbers can be explained as follows:

  • A real number is literally any number you can think of.
  • An imaginary number is a number that gives a negative result when squared.

A real number can be any number. For example, 12, 4.3, -19.0 are all real numbers. Imaginary numbers are shown as i. The following image shows an example of a complex number:

In the example above, 7 is the real number and 3i is the imaginary number. Complex numbers are mostly used in geometry, calculus, scientific calculations, and especially in electronics.

The functions of the Python module aren’t equipped to handle complex numbers. However, Python provides a different module that can specifically deal with complex numbers, the module. The Python module is complemented by the module, which implements many of the same functions but for complex numbers.

You can import the module as follows:

>>>

Since the module is also packaged with Python, you can import it the same way you imported the module. Before you work with the module, you have to know how to define a complex number. You can define a complex number as follows:

>>>

As you can see, you can determine that a number is indeed complex by using .

Note: In mathematics, the imaginary unit is usually denoted i. In some fields, it’s more customary to use j for the same thing. In Python, you use to denote imaginary numbers.

Python also provides a special built-in function called that lets you create complex numbers. You can use as follows:

>>>

You can use either method to create complex numbers. You can also use the module to calculate mathematical functions for complex numbers as follows:

>>>

Python Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in the binary format their values will be 0011 1100 and 0000 1101 respectively. Following table lists out the bitwise operators supported by Python language with an example each in those, we use the above two variables (a and b) as operands −

a = 0011 1100

b = 0000 1101

——————

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a  = 1100 0011

There are following Bitwise operators supported by Python language

Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands (a & b) (means 0000 1100)
| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means 0011 1101)
^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001)
~ Binary Ones Complement It is unary and has the effect of ‘flipping’ bits. (~a ) = -61 (means 1100 0011 in 2’s complement form due to a signed binary number.
<< Binary Left Shift The left operands value is moved left by the number of bits specified by the right operand. a << 2 = 240 (means 1111 0000)
>> Binary Right Shift The left operands value is moved right by the number of bits specified by the right operand. a >> 2 = 15 (means 0000 1111)

9 ответов

Решение

делает целочисленное деление. ,

Таким образом, вы вычисляете x(1/2) в первом случае, x(0) во втором.

Так что это не так, это правильный ответ на другой вопрос.

190

2012-03-07 02:50

Вы должны написать: в противном случае выполняется целочисленное деление и выражение возвращается ,

Это поведение «нормально» в Python 2.x, тогда как в Python 3.x оценивает , Если вы хотите, чтобы ваш код Python 2.x вел себя как 3.x по отношению к делению, напишите — затем будет оценивать и для обратной совместимости, все оценят ,

И для записи, предпочтительный способ вычисления квадратного корня это:

80

2012-03-07 02:51

выполняет целочисленное деление в Python 2:

Если одно из чисел является числом с плавающей точкой, оно работает, как и ожидалось:

10

2012-03-07 02:51

Это тривиальное дополнение к цепочке ответов. Тем не менее, поскольку тема очень популярна в Google, это заслуживает того, чтобы ее добавить, я считаю.

7

2018-04-03 00:11

То, что вы видите, является целочисленным делением. Чтобы получить деление с плавающей запятой по умолчанию,

Или вы можете конвертировать 1 или 2 из 1/2 в значение с плавающей запятой.

6

2012-03-07 02:52

Это может быть немного поздно, чтобы ответить, но самый простой и точный способ вычисления квадратного корня — это метод Ньютона.

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

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

Например, нам нужно найти квадратный корень 30-х годов. Мы знаем, что результат от 5 до 6.

число 30 и оценка 5. Результат каждого рекурсивного вызова:

Последний результат — наиболее точное вычисление квадратного корня числа. Это то же значение, что и встроенная функция math.sqrt().

1

2018-01-25 08:33

Возможно, простой способ запомнить: добавить точку после числителя (или знаменателя)
16**(1./2) #4
289**(1./2) #17
27**(1./3) #3

2018-04-06 02:23

Я надеюсь, что приведенный ниже код ответит на ваш вопрос.

-1

2017-07-25 01:55

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

-1

2017-02-10 17:42

Python NumPy

NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random
Random Intro
Data Distribution
Random Permutation
Seaborn Module
Normal Distribution
Binomial Distribution
Poisson Distribution
Uniform Distribution
Logistic Distribution
Multinomial Distribution
Exponential Distribution
Chi Square Distribution
Rayleigh Distribution
Pareto Distribution
Zipf Distribution

NumPy ufunc
ufunc Intro
ufunc Create Function
ufunc Simple Arithmetic
ufunc Rounding Decimals
ufunc Logs
ufunc Summations
ufunc Products
ufunc Differences
ufunc Finding LCM
ufunc Finding GCD
ufunc Trigonometric
ufunc Hyperbolic
ufunc Set Operations

Python NumPy

NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random
Random Intro
Data Distribution
Random Permutation
Seaborn Module
Normal Distribution
Binomial Distribution
Poisson Distribution
Uniform Distribution
Logistic Distribution
Multinomial Distribution
Exponential Distribution
Chi Square Distribution
Rayleigh Distribution
Pareto Distribution
Zipf Distribution

NumPy ufunc
ufunc Intro
ufunc Create Function
ufunc Simple Arithmetic
ufunc Rounding Decimals
ufunc Logs
ufunc Summations
ufunc Products
ufunc Differences
ufunc Finding LCM
ufunc Finding GCD
ufunc Trigonometric
ufunc Hyperbolic
ufunc Set Operations

Python NumPy

NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random
Random Intro
Data Distribution
Random Permutation
Seaborn Module
Normal Distribution
Binomial Distribution
Poisson Distribution
Uniform Distribution
Logistic Distribution
Multinomial Distribution
Exponential Distribution
Chi Square Distribution
Rayleigh Distribution
Pareto Distribution
Zipf Distribution

NumPy ufunc
ufunc Intro
ufunc Create Function
ufunc Simple Arithmetic
ufunc Rounding Decimals
ufunc Logs
ufunc Summations
ufunc Products
ufunc Differences
ufunc Finding LCM
ufunc Finding GCD
ufunc Trigonometric
ufunc Hyperbolic
ufunc Set Operations

Python NumPy

NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random
Random Intro
Data Distribution
Random Permutation
Seaborn Module
Normal Distribution
Binomial Distribution
Poisson Distribution
Uniform Distribution
Logistic Distribution
Multinomial Distribution
Exponential Distribution
Chi Square Distribution
Rayleigh Distribution
Pareto Distribution
Zipf Distribution

NumPy ufunc
ufunc Intro
ufunc Create Function
ufunc Simple Arithmetic
ufunc Rounding Decimals
ufunc Logs
ufunc Summations
ufunc Products
ufunc Differences
ufunc Finding LCM
ufunc Finding GCD
ufunc Trigonometric
ufunc Hyperbolic
ufunc Set Operations

NumPy vs math#

Several notable Python libraries can be used for mathematical calculations. One of the most prominent libraries is Numerical Python, or NumPy. It is mainly used in scientific computing and in data science fields. Unlike the module, which is part of the standard Python release, you have to install NumPy in order to work with it.

The heart of NumPy is the high-performance N-dimensional (multidimensional) array data structure. This array allows you to perform mathematical operations on an entire array without looping over the elements. All of the functions in the library are optimized to work with the N-dimensional array objects.

Both the module and the NumPy library can be used for mathematical calculations. NumPy has several similarities with the module. NumPy has a subset of functions, similar to module functions, that deal with mathematical calculations. Both NumPy and provide functions that deal with , , , and calculations.

There are also several fundamental differences between and NumPy. The Python module is geared more towards working with scalar values, whereas NumPy is better suited for working with arrays, vectors, and even matrices.

История

Возведение в степень – частный случай умножения, поэтому данную операцию изначально не рассматривали, как самостоятельную. Но уже в работах Диофанта Александрийского степени отведено особое место. В частности «Отец Алгебры» применял понятия кубов и квадратов числа.

Эта операция была известна ещё в древнем Вавилоне, однако современный её вид устоялся лишь в XVII веке.

Как умножение позволяет сократить количество символов сложения:

Так и степень сокращает запись умножения:

  • 6 – это основание;
  • 2 – показатель степени (это число говорит о том, сколько раз число в основании должно быть умножено само на себя).

До воцарения числового показателя, были и другие варианты его записи. Математики раннего Возрождения использовали буквы. Например, Q обозначала квадрат, а C – куб. Различные формы записи возведения в степень не обошли и языки программирования.

Добавить комментарий

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