import math
print('pi is', math.pi)
print('cos(pi) is', math.cos(math.pi))pi is 3.141592653589793
cos(pi) is -1.0
import 명령어를 사용하여 라이브러리를 프로그램으로 불러옵니다.모듈명.기능명 형식으로 사용합니다.import math
print('pi is', math.pi)
print('cos(pi) is', math.cos(math.pi))pi is 3.141592653589793
cos(pi) is -1.0
.)은 해당 모듈에 소속된 요소를 지칭할 때 사용합니다.helphelp() 함수를 사용합니다.help(math)Help on module math:
NAME
math
MODULE REFERENCE
https://docs.python.org/3.11/library/math.html
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.
FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.
The result is between 0 and pi.
acosh(x, /)
Return the inverse hyperbolic cosine of x.
asin(x, /)
Return the arc sine (measured in radians) of x.
The result is between -pi/2 and pi/2.
asinh(x, /)
Return the inverse hyperbolic sine of x.
atan(x, /)
Return the arc tangent (measured in radians) of x.
The result is between -pi/2 and pi/2.
atan2(y, x, /)
Return the arc tangent (measured in radians) of y/x.
Unlike atan(y/x), the signs of both x and y are considered.
atanh(x, /)
Return the inverse hyperbolic tangent of x.
cbrt(x, /)
Return the cube root of x.
ceil(x, /)
Return the ceiling of x as an Integral.
This is the smallest integer >= x.
comb(n, k, /)
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 the
expression (1 + x)**n.
Raises TypeError if either of the arguments are not integers.
Raises ValueError if either of the arguments are negative.
copysign(x, y, /)
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.
cos(x, /)
Return the cosine of x (measured in radians).
cosh(x, /)
Return the hyperbolic cosine of x.
degrees(x, /)
Convert angle x from radians to degrees.
dist(p, q, /)
Return the Euclidean distance between two points p and q.
The points should be specified as sequences (or iterables) of
coordinates. Both inputs must have the same dimension.
Roughly equivalent to:
sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
erf(x, /)
Error function at x.
erfc(x, /)
Complementary error function at x.
exp(x, /)
Return e raised to the power of x.
exp2(x, /)
Return 2 raised to the power of x.
expm1(x, /)
Return exp(x)-1.
This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
fabs(x, /)
Return the absolute value of the float x.
factorial(n, /)
Find n!.
Raise a ValueError if x is negative or non-integral.
floor(x, /)
Return the floor of x as an Integral.
This is the largest integer <= x.
fmod(x, y, /)
Return fmod(x, y), according to platform C.
x % y may differ.
frexp(x, /)
Return the mantissa and exponent of x, as pair (m, e).
m is a float and e is an int, such that x = m * 2.**e.
If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
fsum(seq, /)
Return an accurate floating point sum of values in the iterable seq.
Assumes IEEE-754 floating point arithmetic.
gamma(x, /)
Gamma function at x.
gcd(*integers)
Greatest Common Divisor.
hypot(...)
hypot(*coordinates) -> value
Multidimensional Euclidean distance from the origin to a point.
Roughly equivalent to:
sqrt(sum(x**2 for x in coordinates))
For a two dimensional point (x, y), gives the hypotenuse
using the Pythagorean theorem: sqrt(x*x + y*y).
For example, the hypotenuse of a 3/4/5 right triangle is:
>>> hypot(3.0, 4.0)
5.0
isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
Determine whether two floating point numbers are close in value.
rel_tol
maximum difference for being considered "close", relative to the
magnitude of the input values
abs_tol
maximum difference for being considered "close", regardless of the
magnitude of the input values
Return True if a is close in value to b, and False otherwise.
For the values to be considered close, the difference between them
must be smaller than at least one of the tolerances.
-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
is, NaN is not close to anything, even itself. inf and -inf are
only close to themselves.
isfinite(x, /)
Return True if x is neither an infinity nor a NaN, and False otherwise.
isinf(x, /)
Return True if x is a positive or negative infinity, and False otherwise.
isnan(x, /)
Return True if x is a NaN (not a number), and False otherwise.
isqrt(n, /)
Return the integer part of the square root of the input.
lcm(*integers)
Least Common Multiple.
ldexp(x, i, /)
Return x * (2**i).
This is essentially the inverse of frexp().
lgamma(x, /)
Natural logarithm of absolute value of Gamma function at x.
log(...)
log(x, [base=math.e])
Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
log10(x, /)
Return the base 10 logarithm of x.
log1p(x, /)
Return the natural logarithm of 1+x (base e).
The result is computed in a way which is accurate for x near zero.
log2(x, /)
Return the base 2 logarithm of x.
modf(x, /)
Return the fractional and integer parts of x.
Both results carry the sign of x and are floats.
nextafter(x, y, /)
Return the next floating-point value after x towards y.
perm(n, k=None, /)
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.
pow(x, y, /)
Return x**y (x to the power of y).
prod(iterable, /, *, start=1)
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.
radians(x, /)
Convert angle x from degrees to radians.
remainder(x, y, /)
Difference between x and the closest integer multiple of y.
Return x - n*y where n*y is the closest integer multiple of y.
In the case where x is exactly halfway between two multiples of
y, the nearest even value of n is used. The result is always exact.
sin(x, /)
Return the sine of x (measured in radians).
sinh(x, /)
Return the hyperbolic sine of x.
sqrt(x, /)
Return the square root of x.
tan(x, /)
Return the tangent of x (measured in radians).
tanh(x, /)
Return the hyperbolic tangent of x.
trunc(x, /)
Truncates the Real x to the nearest Integral toward 0.
Uses the __trunc__ magic method.
ulp(x, /)
Return the value of the least significant bit of the float x.
DATA
e = 2.718281828459045
inf = inf
nan = nan
pi = 3.141592653589793
tau = 6.283185307179586
FILE
/home/runner/work/python-novice-gapminder/python-novice-gapminder/.pixi/envs/default/lib/python3.11/lib-dynload/math.cpython-311-x86_64-linux-gnu.so
from ... import ... 구문을 사용하면 모듈 이름을 생략하고 특정 기능만 직접 사용할 수 있습니다.from math import cos, pi
print('cos(pi) is', cos(pi))cos(pi) is -1.0
import ... as ...를 사용하여 모듈 이름을 짧게 줄여서 부를 수 있습니다.import math as m
print('cos(pi) is', m.cos(m.pi))cos(pi) is -1.0
matplotlib.pyplot을 plt로, pandas를 pd로 부르는 것처럼 커뮤니티에서 통용되는 관습적인 별칭을 사용하는 것이 좋습니다.math.sqrt() 함수를 사용하지 않고 제곱근을 구하는 다른 방법은 무엇인가요?sqrt() 함수가 별도로 존재하는 이유는 무엇일까요?math.pow(x, 0.5)를 사용하면 동일한 결과를 얻을 수 있습니다.sqrt(x)가 수식의 의도를 더 직관적으로 보여주며 가독성이 높기 때문입니다. 또한 파이썬이 기반을 둔 C 언어 표준 라이브러리의 구성을 따랐기 때문이기도 합니다.유전자 서열 문자열 bases = 'ACTTGCTTGAC'에서 무작위로 문자 하나를 선택하는 코드를 작성해 보세요.
random 모듈의 choice 함수를 사용하는 것이 가장 간단합니다.
import random
bases = 'ACTTGCTTGAC'
print(random.choice(bases))import math와 from math import *의 차이점은 무엇이며, 왜 후자의 사용을 지양해야 할까요?
import *는 모듈의 모든 기능을 현재 프로그램의 이름 공간으로 가져옵니다. 이는 편리해 보일 수 있지만, 기존에 정의한 변수나 함수 이름과 충돌할 위험이 크고 코드의 출처를 파악하기 어렵게 만듭니다. 따라서 필요한 기능만 명시적으로 임포트하는 것이 권장됩니다.
math.log(0)을 실행했을 때 발생하는 에러의 종류와 의미는 무엇인가요?
ValueError: math domain error가 발생합니다. 이는 로그 함수의 수학적 정의 범위를 벗어난 값이 인수로 전달되었음을 의미합니다.
import를 통해 모듈을 불러오며, from이나 as 키워드로 사용 방식을 조정할 수 있습니다.help()를 통해 라이브러리 사용법을 수시로 확인하는 습관을 들이세요.