diff --git a/TEMA4/Ris1.png b/TEMA4/Ris1.png new file mode 100644 index 0000000..79a2973 Binary files /dev/null and b/TEMA4/Ris1.png differ diff --git a/TEMA4/Ris2.png b/TEMA4/Ris2.png new file mode 100644 index 0000000..a975fc9 Binary files /dev/null and b/TEMA4/Ris2.png differ diff --git a/TEMA4/Ris3.png b/TEMA4/Ris3.png new file mode 100644 index 0000000..d74d7d5 Binary files /dev/null and b/TEMA4/Ris3.png differ diff --git a/TEMA4/Ris4.png b/TEMA4/Ris4.png new file mode 100644 index 0000000..3137547 Binary files /dev/null and b/TEMA4/Ris4.png differ diff --git a/TEMA4/Ris5.png b/TEMA4/Ris5.png new file mode 100644 index 0000000..adafe01 Binary files /dev/null and b/TEMA4/Ris5.png differ diff --git a/TEMA4/report.md b/TEMA4/report.md index 0a95c00..5f2e0d3 100644 --- a/TEMA4/report.md +++ b/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) #Создание графика в оперативной памяти +[] +>>> pylab.title('Первый график') +Text(0.5, 1.0, 'Первый график') +>>> pylab.xlabel('время') +Text(0.5, 0, 'время') +>>> pylab.ylabel('сигнал') +Text(0, 0.5, 'сигнал') +>>> pylab.show() #Отображение графика на экране +``` +Наш график: +![График](Ris1.PNG) +Сохранен в текущем каталоге с именем Ris1. + +Рассмотрим способ построения нескольких графиков на одном рисунке: +```py +>>> X1=[12,6,8,10,7] +>>> X2=[5,7,9,11,13] +>>> pylab.plot(X1) +[] +>>> pylab.plot(X2) +[] +>>> pylab.show() +``` +Графики: +![Рисунок2](Ris2.PNG) + +Теперь изучим возможность построения круговой диаграммы: +```py +>>> region=['Центр','Урал','Сибирь','Юг'] #Метки для диаграммы +>>> naselen=[65,12,23,17] # Значения для диаграммы +>>> pylab.pie(naselen,labels=region) #Создание диаграммы в памяти +([, , , ], [Text(-0.191013134139045, 1.0832885038559115, 'Центр'), Text(-0.861328292412156, -0.6841882582231001, 'Урал'), Text(0.04429273995539947, -1.0991078896938387, 'Сибирь'), Text(0.9873750693480946, -0.48486129194837324, 'Юг')]) +>>> pylab.show() #Отображение диаграммы +``` +![Диаграмма](Ris3.PNG) +Изучим отдельно функции hist и bar: +```py +>>> pylab.hist([1, 1, 1, 2, 2, 3], bins=3) +(array([3., 2., 1.]), array([1. , 1.66666667, 2.33333333, 3. ]), ) +>>> pylab.show() +``` +Гистограмма: +![Гистограмма](Ris4.PNG) +```py +>>> pylab.bar(region, naselen) + +>>> pylab.show() +``` +Столбиковая диаграмма: +![Стобиковая диаграмма](Ris5.PNG) + +## 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 \ No newline at end of file diff --git a/TEMA4/task.md b/TEMA4/task.md new file mode 100644 index 0000000..96f0622 --- /dev/null +++ b/TEMA4/task.md @@ -0,0 +1,57 @@ +# Общее контрольное задание по теме 4 +Киреев Юрий А-02-23 + +## Задание +Реализовать, записать в текстовый файл и проанализировать результаты последовательности инструкций, выполняющих следующие действия: +1. Напишите и исполните единое выражение, реализующее последовательное выполнение следующих операций: вычисление фазы комплексного числа 0.2+0.8j, округление результата до двух знаков после запятой, умножение полученного значения на 20, получение кортежа из двух значений: округленное вниз значение от деления результата на 3 и остатка от этого деления. +2. Создайте объект класса struct_time с временными параметрами для текущего московского времени. Создайте строку с текущим часом и минутами. +3. Создайте список с элементами – названиями дней недели. Сделайте случайную выборку из этого списка с тремя днями недели. +4. Напишите инструкцию случайного выбора числа из последовательности целых чисел от 14 до 32 с шагом 3. +5. Сгенерируйте нормально распределенное число N с математическим ожиданием 15 и стандартным отклонением 4 и округлите его до целого значения. Создайте список с N элементами – случайно выбранными буквами латинского алфавита. +6. Напишите инструкцию для определения временного интервала в минутах, прошедшего с момента предыдущего (из п.2) определения временных параметров. + +## Решение + +1. +```py +>>> import cmath +>>> divmod(round(cmath.phase(0.2+0.8j),2)*20,3) +(8.0, 2.6000000000000014) +``` +2. +```py +>>> import time +>>> localTime = time.localtime() +>>> print("Current time: {}:{}".format(localTime.tm_hour, localTime.tm_min)) +Current time: 19:52 +``` +3. +``` +>>> Days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] +>>> import random +>>> random.sample(Days, 3) +['Wednesday', 'Sunday', 'Friday'] +``` +4. +```py +>>> random.choice(range(14, 33, 3)) +17 +``` +5. +```py +>>> import math +>>> N = math.floor(random.gauss(15, 4)) +>>> N +10 +import string +letters = random.sample(string.ascii_letters, N) +letters +['l', 'x', 'J', 'm', 'K', 'C', 'Z', 'c', 'L', 'G'] +``` +6. +```py +timediff = round(time.time() - time.mktime(localTime)) +print(timediff // 60, "minutes and", timediff % 60, "seconds") +18 minutes and 51 seconds +``` +