ответвлено от main/python-labs
тема4
Этот коммит содержится в:
469
TEMA4/report.md
469
TEMA4/report.md
@@ -148,4 +148,473 @@ import math
|
||||
dir(math)
|
||||
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
|
||||
```
|
||||
Обращение к функциям из импортированного модуля осуществляется с указанием имени модуля, по образцу: <имя модуля>.<имя функции>(<аргументы функции>)
|
||||
|
||||
Изучим функцию расчёта факториала:
|
||||
```py
|
||||
>>> help(math.factorial)
|
||||
Help on built-in function factorial in module math:
|
||||
|
||||
factorial(x, /)
|
||||
Find x!.
|
||||
|
||||
Raise a ValueError if x is negative or non-integral.
|
||||
```
|
||||
Попробуем использовать эту функцию:
|
||||
```py
|
||||
>>>math.factorial(5)
|
||||
120
|
||||
```
|
||||
|
||||
Аналогичным образом изучим и попробуем применить некоторые другие функции из этого модуля:
|
||||
```py
|
||||
>>> help(math.pi)
|
||||
Help on float object:
|
||||
|
||||
class float(object)
|
||||
| float(x=0, /)
|
||||
|
|
||||
| Convert a string or number to a floating point number, if possible.
|
||||
... # огромная справка
|
||||
| real
|
||||
| the real part of a complex number
|
||||
>>> help(math.sin)
|
||||
Help on built-in function sin in module math:
|
||||
|
||||
sin(x, /)
|
||||
Return the sine of x (measured in radians).
|
||||
|
||||
>>> math.sin(math.pi/2)
|
||||
1.0
|
||||
>>>help(math.acos)
|
||||
Help on built-in function acos in module math:
|
||||
|
||||
acos(x, /)
|
||||
Return the arc cosine (measured in radians) of x.
|
||||
|
||||
The result is between 0 and pi.
|
||||
|
||||
>>> math.acos(1)
|
||||
0.0
|
||||
>>>help(math.degrees)
|
||||
Help on built-in function degrees in module math:
|
||||
|
||||
degrees(x, /)
|
||||
Convert angle x from radians to degrees.
|
||||
|
||||
>>> math.degrees(2*math.pi)
|
||||
360.0
|
||||
>>> help(math.radians)
|
||||
Help on built-in function radians in module math:
|
||||
|
||||
radians(x, /)
|
||||
Convert angle x from degrees to radians.
|
||||
|
||||
>>> math.radians(180)
|
||||
3.141592653589793
|
||||
>>> help(math.exp)
|
||||
Help on built-in function exp in module math:
|
||||
|
||||
exp(x, /)
|
||||
Return e raised to the power of x.
|
||||
>>> math.exp(5)
|
||||
148.4131591025766
|
||||
>>> help(math.log)
|
||||
Help on built-in function log in module math:
|
||||
|
||||
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.
|
||||
|
||||
>>> math.log(10)
|
||||
2.302585092994046
|
||||
>>> help(math.log10)
|
||||
Help on built-in function log10 in module math:
|
||||
|
||||
log10(x, /)
|
||||
Return the base 10 logarithm of x.
|
||||
|
||||
>>> math.log10(10)
|
||||
1.0
|
||||
>>> help(math.sqrt)
|
||||
Help on built-in function sqrt in module math:
|
||||
|
||||
sqrt(x, /)
|
||||
Return the square root of x.
|
||||
|
||||
>>> math.sqrt(9)
|
||||
3.0
|
||||
>>> help(math.ceil)
|
||||
Help on built-in function ceil in module math:
|
||||
|
||||
ceil(x, /)
|
||||
Return the ceiling of x as an Integral.
|
||||
|
||||
This is the smallest integer >= x.
|
||||
|
||||
>>> math.ceil(3.14)
|
||||
4
|
||||
>>> help(math.floor)
|
||||
Help on built-in function floor in module math:
|
||||
|
||||
floor(x, /)
|
||||
Return the floor of x as an Integral.
|
||||
|
||||
This is the largest integer <= x.
|
||||
|
||||
>>> math.floor(3.14)
|
||||
3
|
||||
|
||||
```
|
||||
|
||||
## 4. Модуль cmath
|
||||
|
||||
Функции из модуля cmath – совокупность функций для работы с комплексными числами.
|
||||
```py
|
||||
>>> import cmath
|
||||
>>> dir(cmath)
|
||||
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'inf', 'infj', 'isclose', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 'nan', 'nanj', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau']
|
||||
>>> cmath.sqrt(1.2-0.5j) #квадратный корень
|
||||
(1.118033988749895-0.22360679774997896j)
|
||||
>>> cmath.phase(1-0.5j) #расчёт фазы
|
||||
-0.4636476090008061
|
||||
```
|
||||
|
||||
## 5. Модуль random
|
||||
|
||||
Стандартный модуль random – совокупность функций для выполнения операций с псевдослучайными числами и выборками.
|
||||
```py
|
||||
>>> import random
|
||||
>>> dir(random)
|
||||
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_ONE', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_floor', '_index', '_inst', '_isfinite', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randbytes', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
|
||||
```
|
||||
Изучим функцию seed.
|
||||
|
||||
```py
|
||||
>>> help(random.seed)
|
||||
Help on method seed in module random:
|
||||
|
||||
seed(a=None, version=2) method of random.Random instance
|
||||
Initialize internal state from a seed.
|
||||
|
||||
The only supported seed types are None, int, float,
|
||||
str, bytes, and bytearray.
|
||||
|
||||
None or no argument seeds from current time or from an operating
|
||||
system specific randomness source if available.
|
||||
|
||||
If *a* is an int, all bits are used.
|
||||
|
||||
For version 2 (the default), all of the bits are used if *a* is a str,
|
||||
bytes, or bytearray. For version 1 (provided for reproducing random
|
||||
sequences from older versions of Python), the algorithm for str and
|
||||
bytes generates a narrower range of seeds.
|
||||
|
||||
>>> random.seed() #В настоящий момент начальное состояние для псевдослучайных чисел - это системное время
|
||||
```
|
||||
|
||||
Попробуем самостоятельно изучить и применить некоторые функции:
|
||||
```py
|
||||
>>> help(random.random)
|
||||
Help on built-in function random:
|
||||
|
||||
random() method of random.Random instance
|
||||
random() -> x in the interval [0, 1).
|
||||
|
||||
>>> random.random()
|
||||
0.5183251743006774
|
||||
>>> help(random.uniform)
|
||||
Help on method uniform in module random:
|
||||
|
||||
uniform(a, b) method of random.Random instance
|
||||
Get a random number in the range [a, b) or [a, b] depending on rounding.
|
||||
>>> random.uniform(1,2)
|
||||
1.863883074901376
|
||||
>>> help(random.randint)
|
||||
Help on method randint in module random:
|
||||
|
||||
>>> randint(a, b) method of random.Random instance
|
||||
Return random integer in range [a, b], including both end points.
|
||||
|
||||
>>> random.randint(3, 10)
|
||||
7
|
||||
>>> help(random.gauss)
|
||||
Help on method gauss in module random:
|
||||
|
||||
gauss(mu, sigma) method of random.Random instance
|
||||
Gaussian distribution.
|
||||
|
||||
mu is the mean, and sigma is the standard deviation. This is
|
||||
slightly faster than the normalvariate() function.
|
||||
|
||||
Not thread-safe without a lock around calls.
|
||||
|
||||
>>> random.gauss(0,10)
|
||||
-14.080852645068202
|
||||
help(random.choice)
|
||||
Help on method choice in module random:
|
||||
|
||||
choice(seq) method of random.Random instance
|
||||
Choose a random element from a non-empty sequence.
|
||||
>>> numbers = [1, 2, 3, 4, 5]
|
||||
>>> random.choice(numbers)
|
||||
5
|
||||
>>> help(random.shuffle)
|
||||
Help on method shuffle in module random:
|
||||
|
||||
shuffle(x, random=None) method of random.Random instance
|
||||
Shuffle list x in place, and return None.
|
||||
|
||||
Optional argument random is a 0-argument function returning a
|
||||
random float in [0.0, 1.0); if it is the default None, the
|
||||
standard random.random will be used.
|
||||
|
||||
>>> random.shuffle(numbers)
|
||||
>>> numbers
|
||||
[3, 1, 4, 2, 5]
|
||||
>>> help(random.sample)
|
||||
Help on method sample in module random:
|
||||
|
||||
sample(population, k, *, counts=None) method of random.Random instance
|
||||
Chooses k unique random elements from a population sequence or set.
|
||||
|
||||
Returns a new list containing elements from the population while
|
||||
leaving the original population unchanged. The resulting list is
|
||||
in selection order so that all sub-slices will also be valid random
|
||||
samples. This allows raffle winners (the sample) to be partitioned
|
||||
into grand prize and second place winners (the subslices).
|
||||
|
||||
Members of the population need not be hashable or unique. If the
|
||||
population contains repeats, then each occurrence is a possible
|
||||
selection in the sample.
|
||||
|
||||
Repeated elements can be specified one at a time or with the optional
|
||||
counts parameter. For example:
|
||||
|
||||
sample(['red', 'blue'], counts=[4, 2], k=5)
|
||||
|
||||
is equivalent to:
|
||||
|
||||
sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
|
||||
|
||||
To choose a sample from a range of integers, use range() for the
|
||||
population argument. This is especially fast and space efficient
|
||||
for sampling from a large population:
|
||||
|
||||
sample(range(10000000), 60)
|
||||
|
||||
>>> random.sample(numbers,3)
|
||||
[2, 5, 1]
|
||||
>>> help(random.betavariate)
|
||||
Help on method betavariate in module random:
|
||||
|
||||
betavariate(alpha, beta) method of random.Random instance
|
||||
Beta distribution.
|
||||
|
||||
Conditions on the parameters are alpha > 0 and beta > 0.
|
||||
Returned values range between 0 and 1.
|
||||
|
||||
>>> random.betavariate(1, 10)
|
||||
0.0334849854614458
|
||||
>>> help(random.gammavariate)
|
||||
Help on method gammavariate in module random:
|
||||
|
||||
gammavariate(alpha, beta) method of random.Random instance
|
||||
Gamma distribution. Not the gamma function!
|
||||
|
||||
Conditions on the parameters are alpha > 0 and beta > 0.
|
||||
|
||||
The probability distribution function is:
|
||||
|
||||
x ** (alpha - 1) * math.exp(-x / beta)
|
||||
pdf(x) = --------------------------------------
|
||||
math.gamma(alpha) * beta ** alpha
|
||||
|
||||
>>> random.gammavariate(1,10)
|
||||
21.801817565886562
|
||||
```
|
||||
Создадим список с 4 случайными значениями, подчиняющимися, соответственно, равномерному, нормальному, бета и гамма – распределениям и с любыми допустимыми значениями параметров этих распределений.
|
||||
|
||||
```py
|
||||
rand_spis = [random.random(), random.uniform(1,2), random.betavariate(1, 10), random.gammavariate(1,10)]
|
||||
rand_spis
|
||||
[0.855682663095964, 1.3318533389175167, 0.08901765537251825, 5.945577224669993]
|
||||
```
|
||||
|
||||
## 6. Модуль time
|
||||
|
||||
Работа с календарем и со временем.
|
||||
```py
|
||||
>>> import time
|
||||
>>> dir(time)
|
||||
['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'monotonic_ns', 'perf_counter', 'perf_counter_ns', 'process_time', 'process_time_ns', 'sleep', 'strftime', 'strptime', 'struct_time', 'thread_time', 'thread_time_ns', 'time', 'time_ns', 'timezone', 'tzname']
|
||||
```
|
||||
|
||||
Изучим функцию time, возвращающую время в секундах, прошедшее с начала эпохи, за которое обычно принимается 1.01.1970г.
|
||||
|
||||
```py
|
||||
>>> c1=time.time()
|
||||
>>> c1
|
||||
1760885662.4458969
|
||||
>>> c2=time.time()-c1 #время со ввода предыдущей инструкции
|
||||
>>> c2
|
||||
13.31933856010437
|
||||
```
|
||||
|
||||
Изучим функцию gmtime:
|
||||
|
||||
```py
|
||||
>>> help(time.gmtime)
|
||||
Help on built-in function gmtime in module time:
|
||||
|
||||
gmtime(...)
|
||||
gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
|
||||
tm_sec, tm_wday, tm_yday, tm_isdst)
|
||||
|
||||
Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
|
||||
GMT). When 'seconds' is not passed in, convert the current time instead.
|
||||
|
||||
If the platform supports the tm_gmtoff and tm_zone, they are available as
|
||||
attributes only.
|
||||
|
||||
>>> dat=time.gmtime()
|
||||
>>> dat
|
||||
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=19, tm_hour=14, tm_min=57, tm_sec=31, tm_wday=6, tm_yday=292, tm_isdst=0)
|
||||
>>> dat.tm_mon
|
||||
10
|
||||
```
|
||||
Для получения местного времени применим функцию localtime
|
||||
```py
|
||||
dat2 = time.localtime()
|
||||
dat2
|
||||
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=19, tm_hour=17, tm_min=59, tm_sec=55, tm_wday=6, tm_yday=292, tm_isdst=0)
|
||||
```
|
||||
Попробуем изучить и применить другие функции модуля time:
|
||||
|
||||
```py
|
||||
>>> help(time.asctime)
|
||||
Help on built-in function asctime in module time:
|
||||
|
||||
asctime(...)
|
||||
asctime([tuple]) -> string
|
||||
|
||||
Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
|
||||
When the time tuple is not present, current time as returned by localtime()
|
||||
is used.
|
||||
|
||||
>>> time.asctime(dat)
|
||||
'Sun Oct 19 14:57:31 2025'
|
||||
>>> help(time.ctime)
|
||||
Help on built-in function ctime in module time:
|
||||
|
||||
>>> ctime(...)
|
||||
ctime(seconds) -> string
|
||||
|
||||
Convert a time in seconds since the Epoch to a string in local time.
|
||||
This is equivalent to asctime(localtime(seconds)). When the time tuple is
|
||||
not present, current time as returned by localtime() is used.
|
||||
|
||||
>>> time.ctime(c1)
|
||||
'Sun Oct 19 17:54:22 2025'
|
||||
help(time.sleep)
|
||||
Help on built-in function sleep in module time:
|
||||
|
||||
sleep(...)
|
||||
sleep(seconds)
|
||||
|
||||
Delay execution for a given number of seconds. The argument may be
|
||||
a floating point number for subsecond precision.
|
||||
|
||||
time.sleep(1) #произошла пауза в IDLE на 1 секунду
|
||||
>>> help(time.mktime)
|
||||
Help on built-in function mktime in module time:
|
||||
|
||||
mktime(...)
|
||||
mktime(tuple) -> floating point number
|
||||
|
||||
Convert a time tuple in local time to seconds since the Epoch.
|
||||
Note that mktime(gmtime(0)) will not generally return zero for most
|
||||
time zones; instead the returned value will either be equal to that
|
||||
of the timezone or altzone attributes on the time module.
|
||||
|
||||
>>> time.mktime(dat)
|
||||
1760875051.0
|
||||
>>> time.localtime(c1)
|
||||
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=19, tm_hour=17, tm_min=54, tm_sec=22, tm_wday=6, tm_yday=292, tm_isdst=0)
|
||||
```
|
||||
|
||||
## 7. Графические функции
|
||||
```py
|
||||
>>> import pylab #импортируем модуль
|
||||
>>> x=list(range(-3,55,4))
|
||||
>>> t=list(range(15))
|
||||
>>> x,t
|
||||
([-3, 1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
|
||||
>>> pylab.plot(t,x) #Создание графика в оперативной памяти
|
||||
[<matplotlib.lines.Line2D object at 0x00000208629323B0>]
|
||||
>>> pylab.title('Первый график')
|
||||
Text(0.5, 1.0, 'Первый график')
|
||||
>>> pylab.xlabel('время')
|
||||
Text(0.5, 0, 'время')
|
||||
>>> pylab.ylabel('сигнал')
|
||||
Text(0, 0.5, 'сигнал')
|
||||
>>> pylab.show() #Отображение графика на экране
|
||||
```
|
||||
Наш график:
|
||||

|
||||
Сохранен в текущем каталоге с именем Ris1.
|
||||
|
||||
Рассмотрим способ построения нескольких графиков на одном рисунке:
|
||||
```py
|
||||
>>> X1=[12,6,8,10,7]
|
||||
>>> X2=[5,7,9,11,13]
|
||||
>>> pylab.plot(X1)
|
||||
[<matplotlib.lines.Line2D object at 0x00000208655097B0>]
|
||||
>>> pylab.plot(X2)
|
||||
[<matplotlib.lines.Line2D object at 0x0000020865509AB0>]
|
||||
>>> pylab.show()
|
||||
```
|
||||
Графики:
|
||||

|
||||
|
||||
Теперь изучим возможность построения круговой диаграммы:
|
||||
```py
|
||||
>>> region=['Центр','Урал','Сибирь','Юг'] #Метки для диаграммы
|
||||
>>> naselen=[65,12,23,17] # Значения для диаграммы
|
||||
>>> pylab.pie(naselen,labels=region) #Создание диаграммы в памяти
|
||||
([<matplotlib.patches.Wedge object at 0x000002086B0C6E60>, <matplotlib.patches.Wedge object at 0x000002086B0C6DA0>, <matplotlib.patches.Wedge object at 0x000002086B0C78B0>, <matplotlib.patches.Wedge object at 0x000002086B0C7DF0>], [Text(-0.191013134139045, 1.0832885038559115, 'Центр'), Text(-0.861328292412156, -0.6841882582231001, 'Урал'), Text(0.04429273995539947, -1.0991078896938387, 'Сибирь'), Text(0.9873750693480946, -0.48486129194837324, 'Юг')])
|
||||
>>> pylab.show() #Отображение диаграммы
|
||||
```
|
||||

|
||||
Изучим отдельно функции hist и bar:
|
||||
```py
|
||||
>>> pylab.hist([1, 1, 1, 2, 2, 3], bins=3)
|
||||
(array([3., 2., 1.]), array([1. , 1.66666667, 2.33333333, 3. ]), <BarContainer object of 3 artists>)
|
||||
>>> pylab.show()
|
||||
```
|
||||
Гистограмма:
|
||||

|
||||
```py
|
||||
>>> pylab.bar(region, naselen)
|
||||
<BarContainer object of 4 artists>
|
||||
>>> pylab.show()
|
||||
```
|
||||
Столбиковая диаграмма:
|
||||

|
||||
|
||||
## 8. Модуль statistic
|
||||
```py
|
||||
>>> import statistics
|
||||
>>> dir(statistics)
|
||||
['Counter', 'Decimal', 'Fraction', 'LinearRegression', 'NormalDist', 'StatisticsError', '_SQRT2', '__all__', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_coerce', '_convert', '_decimal_sqrt_of_frac', '_exact_ratio', '_fail_neg', '_float_sqrt_of_frac', '_integer_sqrt_of_frac_rto', '_isfinite', '_mean_stdev', '_normal_dist_inv_cdf', '_sqrt_bit_width', '_ss', '_sum', 'bisect_left', 'bisect_right', 'correlation', 'covariance', 'defaultdict', 'erf', 'exp', 'fabs', 'fmean', 'fsum', 'geometric_mean', 'groupby', 'harmonic_mean', 'hypot', 'linear_regression', 'log', 'math', 'mean', 'median', 'median_grouped', 'median_high', 'median_low', 'mode', 'mul', 'multimode', 'namedtuple', 'numbers', 'pstdev', 'pvariance', 'quantiles', 'random', 'reduce', 'repeat', 'sqrt', 'stdev', 'sys', 'tau', 'variance']
|
||||
>>> statistics.mean([1, 2, 3, 4, 5, 6, 7, 8, 9]) # Вычисление среднего
|
||||
5
|
||||
>>> statistics.stdev([1, 2, 3, 4, 5, 6, 7, 8, 9]) # Вычисление среднеквадратичного отклонения
|
||||
2.7386127875258306
|
||||
>>> statistics.median([1, 2, 3, 4, 5, 6, 7, 8]) # Вычисление медианы
|
||||
4.5
|
||||
```
|
||||
|
||||
## 9. Завершил сеанс работы с IDLE
|
||||
Ссылка в новой задаче
Block a user