在 Python 中使用欧拉数
欧拉数或 e 是数学中最基本的常数之一,就像 pi 一样。e 是自然对数函数的基础。它是代表指数常数的无理数。
本教程将演示如何在 Python 中复制欧拉数(e)。
有三种常见的方法来获取欧拉数并将其用于 Python 中的方程式。
- 使用
math.e - 使用
math.exp() - 使用
numpy.exp()
在 Python 中使用 math.e 来获取欧拉数
Python 模块 math 包含许多可用于方程式的数学常数。欧拉数或 e 是 math 模块具有的常数之一。
from math import e
print(e)
输出:
2.718281828459045
上面的输出是 e 常数的基值。
作为一个示例方程式,让我们创建一个函数,以将 e^n 或 e 的值转换为数字 n 的幂,其中 n = 3。
另外,请注意,Python 中幂运算的语法是双星号**。
from math import e
def getExp(n):
return e ** n
print(getExp(3))
输出:
20.085536923187664
如果你希望控制结果的小数位数,则可以通过将值格式化为字符串并在格式化后将其打印出来来实现。
要将浮点值的格式设置为小数位数 n,我们可以在字符串上使用 format() 函数,语法为 {:.nf},其中 n 是要显示的小数位数。
例如,使用上面的相同示例,将输出格式设置为 5 个小数位。
def getExp(n):
return "{:.5f}".format(e ** n)
print(getExp(3))
输出:
20.08554
在 Python 中使用 math.exp() 来获取欧拉数
math 模块还具有一个称为 exp() 的函数,该函数将 e 的值返回为数字的幂。与 math.e 相比,exp() 函数的执行速度大大提高,并且包含可验证给定 number 参数的代码。
对于此示例,请尝试使用十进制数字作为参数。
import math
print(math.exp(7.13))
输出:
1248.8769669132553
另一个示例是通过将参数设置为 1 来确定该值,从而获得 e 的实际基准值。
import math
print(math.exp(1))
输出:
2.718281828459045
输出是 e 的实际值,设置为小数点后 15 位。
在 Python 中使用 numpy.exp() 来获取欧拉数
NumPy 模块中的 exp() 函数也执行与 math.exp() 相同的操作并接受相同的参数。
不同之处在于,它的执行速度比 math.e 和 math.exp() 都快,而 math.exp() 仅接受标量数,而 numpy.exp() 接受标量数和矢量例如数组和集合。
例如,使用 numpy.exp() 函数来接受浮点数数组和单个整数值。
import numpy as np
arr = [3.0, 5.9, 6.52, 7.13]
singleVal = 2
print(np.exp(arr))
print(np.exp(singleVal))
输出:
[20.08553692 365.03746787 678.57838534 1248.87696691]
7.38905609893065
如果将数字数组用作参数,则它将返回 e 常量结果数组,该数组的值提高到给定数组中所有值的幂。如果给定单个数字作为参数,则其行为将与 math.exp() 完全相同。
总之,要获取 Python 中的欧拉数或 e,请使用 math.e。使用 math.exp() 将需要一个数字作为参数以用作指数值,而将 e 作为其基值。
使用 exp() 来计算双星号上的 e 的指数时,**的效果要优于后者,因此,如果要处理大量数字,则最好使用 math.exp()。
另一种选择是使用 numpy.exp(),它支持数字数组作为参数,并且比 math 模块中的两种解决方案都执行得更快。因此,如果方程式中包含向量,请改用 numpy.exp()。
Skilled in Python, Java, Spring Boot, AngularJS, and Agile Methodologies. Strong engineering professional with a passion for development and always seeking opportunities for personal and career growth. A Technical Writer writing about comprehensive how-to articles, environment set-ups, and technical walkthroughs. Specializes in writing Python, Java, Spring, and SQL articles.
LinkedIn