Конечно! Я добавил необходимые разделы и функции в ваш модуль mathematic.lua. Поскольку реализация всех перечисленных функций обширна, я включил основные примеры для каждой категории. Вы можете дополнить их по аналогии в зависимости от ваших потребностей.
-- mathematic.lua
local mathematic = {}
-- =======================
-- Константы
-- =======================
-- Приближение числа пи с использованием ряда Нилаканта (быстрее сходится, чем ряд Лейбница)
local function calculate_pi(iterations)
local pi = 3
local sign = 1
local denominator = 2
for _ = 1, iterations do
pi = pi + sign * (4 / (denominator * (denominator + 1) * (denominator + 2)))
sign = -sign
denominator = denominator + 2
end
return pi
end
mathematic.pi = calculate_pi(100000) -- Чем больше итераций, тем точнее pi
-- Определение бесконечности
mathematic.infinity = 1 / 0
-- =======================
-- Алгебраические функции
-- =======================
-- Абсолютное значение числа
function mathematic.abs(x)
return x >= 0 and x or -x
end
-- Возведение числа 'a' в степень 'b' (целая степень)
function mathematic.power(a, b)
if b == 0 then
return 1
elseif b < 0 then
return 1 / mathematic.power(a, -b)
else
local result = 1
for _ = 1, b do
result = result * a
end
return result
end
end
-- Вычисление факториала числа 'n'
function mathematic.factorial(n)
if n < 0 then
error("Factorial is not defined for negative numbers")
end
local result = 1
for i = 2, n do
result = result * i
end
return result
end
-- Округление числа до ближайшего целого вниз
function mathematic.floor(x)
if x >= 0 then
local integer_part = 0
while integer_part + 1 <= x do
integer_part = integer_part + 1
end
return integer_part
else
local integer_part = 0
while integer_part - 1 >= x do
integer_part = integer_part - 1
end
return integer_part
end
end
-- Остаток от деления 'a' на 'b'
function mathematic.mod(a, b)
if b == 0 then
error("Modulo by zero")
end
return a - mathematic.floor(a / b) * b
end
-- Приведение числа к целой части
function mathematic.int(x)
return mathematic.floor(x)
end
-- Нахождение наибольшего общего делителя (НОД) двух чисел
function mathematic.gcd(a, b)
a = mathematic.abs(a)
b = mathematic.abs(b)
while b ~= 0 do
a, b = b, mathematic.mod(a, b)
end
return a
end
-- Нахождение наименьшего общего кратного (НОК) двух чисел
function mathematic.lcm(a, b)
if a == 0 or b == 0 then
return 0
end
return mathematic.abs((a * b) / mathematic.gcd(a, b))
end
-- =======================
-- Тригонометрические функции
-- =======================
-- Преобразование градусов в радианы
function mathematic.deg_to_rad(degrees)
return degrees * mathematic.pi / 180
end
-- Преобразование радианов в градусы
function mathematic.rad_to_deg(radians)
return radians * 180 / mathematic.pi
end
-- Вычисление синуса с использованием ряда Тейлора
function mathematic.sin(x)
-- Приведение x к диапазону [-pi, pi] для улучшения сходимости ряда
x = x % (2 * mathematic.pi)
if x > mathematic.pi then
x = x - 2 * mathematic.pi
elseif x < -mathematic.pi then
x = x + 2 * mathematic.pi
end
local term = x -- Первый член ряда
local sum = term
local n = 1
local sign = -1
while mathematic.abs(term) > 1e-10 do
term = mathematic.power(x, 2 * n + 1) / mathematic.factorial(2 * n + 1)
sum = sum + sign * term
sign = -sign
n = n + 1
end
return sum
end
-- Вычисление косинуса с использованием ряда Тейлора
function mathematic.cos(x)
-- Приведение x к диапазону [-pi, pi] для улучшения сходимости ряда
x = x % (2 * mathematic.pi)
if x > mathematic.pi then
x = x - 2 * mathematic.pi
elseif x < -mathematic.pi then
x = x + 2 * mathematic.pi
end
local term = 1 -- Первый член ряда
local sum = term
local n = 1
local sign = -1
while mathematic.abs(term) > 1e-10 do
term = mathematic.power(x, 2 * n) / mathematic.factorial(2 * n)
sum = sum + sign * term
sign = -sign
n = n + 1
end
return sum
end
-- Вычисление тангенса как отношение синуса к косинусу
function mathematic.tan(x)
local cosx = mathematic.cos(x)
if cosx == 0 then
return mathematic.sin(x) > 0 and mathematic.infinity or -mathematic.infinity
end
return mathematic.sin(x) / cosx
end
-- Котангенс
function mathematic.cot(x)
local sinx = mathematic.sin(x)
local cosx = mathematic.cos(x)
if sinx == 0 then
return mathematic.infinity
end
return cosx / sinx
end
-- Секанс
function mathematic.sec(x)
local cosx = mathematic.cos(x)
if cosx == 0 then
return mathematic.infinity
end
return 1 / cosx
end
-- Косеканс
function mathematic.csc(x)
local sinx = mathematic.sin(x)
if sinx == 0 then
return mathematic.infinity
end
return 1 / sinx
end
-- Гиперболические функции
function mathematic.sinh(x)
return (mathematic.exp(x) - mathematic.exp(-x)) / 2
end
function mathematic.cosh(x)
return (mathematic.exp(x) + mathematic.exp(-x)) / 2
end
function mathematic.tanh(x)
local coshx = mathematic.cosh(x)
if coshx == 0 then
return mathematic.infinity
end
return mathematic.sinh(x) / coshx
end
function mathematic.asinh(x)
return mathematic.ln(x + mathematic.sqrt(x * x + 1))
end
function mathematic.acosh(x)
if x < 1 then
error("acosh undefined for x < 1")
end
return mathematic.ln(x + mathematic.sqrt(x * x - 1))
end
function mathematic.atanh(x)
if x <= -1 or x >= 1 then
error("atanh undefined for |x| >= 1")
end
return 0.5 * mathematic.ln((1 + x) / (1 - x))
end
-- =======================
-- Обратные тригонометрические функции
-- =======================
-- Арксинус с использованием метода Ньютона
function mathematic.asin(x)
if x < -1 or x > 1 then
error("Asin undefined for |x| > 1")
end
if x == 1 then
return mathematic.pi / 2
elseif x == -1 then
return -mathematic.pi / 2
end
-- Начальное приближение
local guess = x
-- Метод Ньютона
for _ = 1, 100 do
local f = mathematic.sin(guess) - x
local f_derivative = mathematic.cos(guess)
if f_derivative == 0 then
break
end
local new_guess = guess - f / f_derivative
if mathematic.abs(new_guess - guess) < 1e-10 then
return new_guess
end
guess = new_guess
end
return guess
end
-- Арккосинус как pi/2 - арксинус(x)
function mathematic.acos(x)
return mathematic.pi / 2 - mathematic.asin(x)
end
-- Арктангенс с использованием метода Ньютона
function mathematic.atan(x)
-- Специальный случай для бесконечности
if x == mathematic.infinity then
return mathematic.pi / 2
elseif x == -mathematic.infinity then
return -mathematic.pi / 2
end
-- Начальное приближение
local guess = x
-- Метод Ньютона
for _ = 1, 100 do
local sine = mathematic.sin(guess)
local cosine = mathematic.cos(guess)
local f = sine / cosine - x
local cosine_sq = mathematic.power(cosine, 2)
if cosine_sq == 0 then
break
end
-- Производная функции f = tan(x) - a
local f_derivative = 1 / cosine_sq
local new_guess = guess - f / f_derivative
if mathematic.abs(new_guess - guess) < 1e-10 then
return new_guess
end
guess = new_guess
end
return guess
end
-- Арккотангенс
function mathematic.acot(x)
return mathematic.pi / 2 - mathematic.atan(x)
end
-- Арксеканс
function mathematic.asec(x)
if x == 0 then
error("asec undefined for x = 0")
end
return mathematic.acos(1 / x)
end
-- Арккосеканс
function mathematic.acsc(x)
if x == 0 then
error("acsc undefined for x = 0")
end
return mathematic.asin(1 / x)
end
-- =======================
-- Полиномиальные функции
-- =======================
-- Вычисление значения полинома по коэффициентам и значению x
-- coefficients: таблица с коэффициентами от свободного члена до старшего
function mathematic.evaluate_polynomial(coefficients, x)
local result = 0
for i = #coefficients, 1, -1 do
result = result * x + coefficients[i]
end
return result
end
-- Решение квадратного уравнения ax^2 + bx + c = 0
function mathematic.solve_quadratic(a, b, c)
if a == 0 then
if b == 0 then
error("No solution")
else
return -c / b
end
end
local discriminant = mathematic.pow(b, 2) - 4 * a * c
if discriminant > 0 then
local sqrt_d = mathematic.sqrt(discriminant)
return (-b + sqrt_d) / (2 * a), (-b - sqrt_d) / (2 * a)
elseif discriminant == 0 then
return -b / (2 * a)
else
return nil, nil -- Нет действительных корней
end
end
-- Решение кубического уравнения ax^3 + bx^2 + cx + d = 0
function mathematic.solve_cubic(a, b, c, d)
if a == 0 then
return mathematic.solve_quadratic(b, c, d)
end
-- Нормализация
b = b / a
c = c / a
d = d / a
local Q = (3 * c - mathematic.power(b, 2)) / 9
local R = (9 * b * c - 27 * d - 2 * mathematic.power(b, 3)) / 54
local D = mathematic.power(Q, 3) + mathematic.power(R, 2) -- дискриминант
if D >= 0 then
local S = mathematic.cbrt(R + mathematic.sqrt(D))
local T = mathematic.cbrt(R - mathematic.sqrt(D))
return S + T - b / 3
else
local theta = mathematic.acos(R / mathematic.sqrt(mathematic.power(Q, 3)))
return 2 * mathematic.sqrt(Q) * mathematic.cos(theta / 3) - b / 3
end
end
-- Факториал для полей (на основе гамма-функции)
function mathematic.factorial_field(n)
return mathematic.gamma(n + 1)
end
-- Разложение многочлена на множители (пример для простых корней)
function mathematic.factorize_polynomial(coefficients)
-- Это простая реализация для поиска рациональных корней методом рациональных корней
local roots = {}
local a0 = coefficients[1]
local an = coefficients[#coefficients]
local function possible_roots()
local factors_a0 = {}
local factors_an = {}
for i = 1, mathematic.abs(a0) do
if a0 % i == 0 then
table.insert(factors_a0, i)
table.insert(factors_a0, -i)
end
end
for i = 1, mathematic.abs(an) do
if an % i == 0 then
table.insert(factors_an, i)
table.insert(factors_an, -i)
end
end
local candidates = {}
for _, p in ipairs(factors_a0) do
for _, q in ipairs(factors_an) do
if q ~= 0 then
table.insert(candidates, p / q)
end
end
end
return candidates
end
local candidates = possible_roots()
for _, r in ipairs(candidates) do
if mathematic.abs(mathematic.evaluate_polynomial(coefficients, r)) < 1e-6 then
table.insert(roots, r)
-- Деление многочлена на (x - r) можно добавить для дальнейшего факторизации
end
end
return roots
end
-- =======================
-- Линейная алгебра
-- =======================
-- Векторы и операции с ними
-- Сложение двух векторов
function mathematic.vector_add(v1, v2)
if #v1 ~= #v2 then
error("Vectors must be of the same length")
end
local result = {}
for i = 1, #v1 do
result[i] = v1[i] + v2[i]
end
return result
end
-- Скалярное произведение двух векторов
function mathematic.dot_product(v1, v2)
if #v1 ~= #v2 then
error("Vectors must be of the same length")
end
local result = 0
for i = 1, #v1 do
result = result + v1[i] * v2[i]
end
return result
end
-- Векторное произведение (только для 3-мерных векторов)
function mathematic.cross_product(v1, v2)
if #v1 ~= 3 or #v2 ~= 3 then
error("Cross product is defined for 3-dimensional vectors only")
end
return {
v1[2] * v2[3] - v1[3] * v2[2],
v1[3] * v2[1] - v1[1] * v2[3],
v1[1] * v2[2] - v1[2] * v2[1]
}
end
-- Матрицы и операции с ними
-- Сложение двух матриц
function mathematic.matrix_add(m1, m2)
local rows = #m1
local cols = #m1[1]
if rows ~= #m2 or cols ~= #m2[1] then
error("Matrices must have the same dimensions")
end
local result = {}
for i = 1, rows do
result[i] = {}
for j = 1, cols do
result[i][j] = m1[i][j] + m2[i][j]
end
end
return result
end
-- Умножение двух матриц
function mathematic.matrix_multiply(m1, m2)
local rows_m1 = #m1
local cols_m1 = #m1[1]
local rows_m2 = #m2
local cols_m2 = #m2[1]
if cols_m1 ~= rows_m2 then
error("Number of columns of first matrix must equal number of rows of second matrix")
end
local result = {}
for i = 1, rows_m1 do
result[i] = {}
for j = 1, cols_m2 do
local sum = 0
for k = 1, cols_m1 do
sum = sum + m1[i][k] * m2[k][j]
end
result[i][j] = sum
end
end
return result
end
-- Транспонирование матрицы
function mathematic.matrix_transpose(m)
local rows = #m
local cols = #m[1]
local result = {}
for i = 1, cols do
result[i] = {}
for j = 1, rows do
result[i][j] = m[j][i]
end
end
return result
end
-- Вычисление определителя матрицы (для квадратных матриц)
function mathematic.matrix_determinant(m)
local n = #m
for i = 1, n do
if #m[i] ~= n then
error("Determinant is defined for square matrices only")
end
end
if n == 1 then
return m[1][1]
elseif n == 2 then
return m[1][1]*m[2][2] - m[1][2]*m[2][1]
else
local det = 0
for col = 1, n do
local submatrix = {}
for i = 2, n do
submatrix[i-1] = {}
local subcol = 1
for j = 1, n do
if j ~= col then
submatrix[i-1][subcol] = m[i][j]
subcol = subcol + 1
end
end
end
det = det + ((col % 2 == 1) and 1 or -1) * m[1][col] * mathematic.matrix_determinant(submatrix)
end
return det
end
end
-- Вычисление обратной матрицы (для квадратных матриц)
function mathematic.matrix_inverse(m)
local det = mathematic.matrix_determinant(m)
if det == 0 then
error("Matrix is singular and cannot be inverted")
end
local n = #m
local adjugate = {}
for i = 1, n do
adjugate[i] = {}
for j = 1, n do
-- Минор элемента (j, i) для транспонирования
local submatrix = {}
for row = 1, n do
if row ~= j then
submatrix[#submatrix + 1] = {}
for col = 1, n do
if col ~= i then
table.insert(submatrix[#submatrix], m[row][col])
end
end
end
end
adjugate[i][j] = mathematic.pow(-1, i + j) * mathematic.matrix_determinant(submatrix)
end
end
-- Деление каждого элемента аджугатной матрицы на детерминант
for i = 1, n do
for j = 1, n do
adjugate[i][j] = adjugate[i][j] / det
end
end
return adjugate
end
-- Решение системы линейных уравнений методом Гаусса
-- Матрица системы в виде таблицы, где последняя колонка - свободные члены
function mathematic.gauss_solve(matrix)
local n = #matrix
for i = 1, n do
-- Поиск максимального элемента для выбора опорного
local max_el = mathematic.abs(matrix[i][i])
local max_row = i
for k = i+1, n do
if mathematic.abs(matrix[k][i]) > max_el then
max_el = mathematic.abs(matrix[k][i])
max_row = k
end
end
-- Перестановка строк
for k = i, n+1 do
matrix[max_row][k], matrix[i][k] = matrix[i][k], matrix[max_row][k]
end
-- Приведение к верхнетреугольному виду
for k = i+1, n do
local c = matrix[k][i] / matrix[i][i]
for j = i, n+1 do
matrix[k][j] = matrix[k][j] - c * matrix[i][j]
end
end
end
-- Обратный ход
local x = {}
for i = n, 1, -1 do
x[i] = matrix[i][n+1]
for j = i+1, n do
x[i] = x[i] - matrix[i][j] * x[j]
end
x[i] = x[i] / matrix[i][i]
end
return x
end
-- Решение системы линейных уравнений методом Крамера
function mathematic.cramer_solve(matrix)
local n = #matrix
local det = mathematic.matrix_determinant(mathematic.matrix_sub(matrix, false))
if det == 0 then
error("System has no unique solution")
end
local solutions = {}
for i = 1, n do
local modified = mathematic.matrix_copy(mathematic.matrix_sub(matrix, false))
for j = 1, n do
modified[j][i] = matrix[j][n+1]
end
solutions[i] = mathematic.matrix_determinant(modified) / det
end
return solutions
end
-- Вспомогательные функции для линейной алгебры
function mathematic.matrix_sub(matrix, include_last_column)
local submatrix = {}
local n = #matrix
local m = #matrix[1]
for i = 1, n do
submatrix[i] = {}
for j = 1, (include_last_column and m or m-1) do
submatrix[i][j] = matrix[i][j]
end
end
return submatrix
end
function mathematic.matrix_copy(matrix)
local copy = {}
for i, row in ipairs(matrix) do
copy[i] = {}
for j, val in ipairs(row) do
copy[i][j] = val
end
end
return copy
end
-- =======================
-- Тригонометрические функции (Дополнительно)
-- =======================
-- Многоугольные формулы
-- Формула суммы синусов
function mathematic.sin_sum(a, b)
return mathematic.sin(a) + mathematic.sin(b)
end
-- Формула произведения синусов
function mathematic.sin_product(a, b)
return (mathematic.cos(a - b) - mathematic.cos(a + b)) / 2
end
-- Тождественные преобразования
function mathematic.sin_double_angle(x)
return 2 * mathematic.sin(x) * mathematic.cos(x)
end
function mathematic.cos_double_angle(x)
return mathematic.cos(x)^2 - mathematic.sin(x)^2
end
-- =======================
-- Специальные функции
-- =======================
-- Функции Бесселя первого рода первого вида (приближенная реализация)
function mathematic.bessel_j(n, x)
local sum = 0
for k = 0, 20 do -- Ограничение числа членов ряда
local term = (mathematic.power(-1, k) / (mathematic.factorial(k) * mathematic.factorial(k + n))) * mathematic.power(x / 2, 2 * k + n)
sum = sum + term
end
return sum
end
-- Функции Бесселя второго рода первого вида (приближенная реализация)
function mathematic.bessel_y(n, x)
-- Используем формулу через функции Бесселя первого рода
if x == 0 then
error("Y функции Бесселя имеют сингулярности в нуле")
end
local jn = mathematic.bessel_j(n, x)
local jn_neg = mathematic.bessel_j(-n, x)
return (jn * mathematic.cos(n * mathematic.pi) - jn_neg) / mathematic.sin(n * mathematic.pi)
end
-- Гамма-функция (для положительных чисел, приближенная реализация)
function mathematic.gamma(x)
-- Формула Стирлинга
if x <= 0 then
error("Gamma function is not defined for non-positive values")
end
return mathematic.sqrt(2 * mathematic.pi / x) * mathematic.power((x / mathematic.e), x)
end
-- Функция Римана Зета (приближенная реализация для s > 1)
function mathematic.zeta(s)
if s <= 1 then
error("Riemann Zeta function is defined for s > 1")
end
local sum = 0
for n = 1, 100000 do -- Ограничение числа членов ряда
sum = sum + 1 / mathematic.power(n, s)
end
return sum
end
-- =======================
-- Анализ и высшая математика
-- =======================
-- Численные методы интегрирования
-- Метод трапеций
function mathematic.trapezoidal(f, a, b, n)
local h = (b - a) / n
local sum = 0.5 * (f(a) + f(b))
for i = 1, n-1 do
sum = sum + f(a + i * h)
end
return sum * h
end
-- Метод Симпсона
function mathematic.simpson(f, a, b, n)
if n % 2 ~= 0 then
error("Number of intervals must be even for Simpson's rule")
end
local h = (b - a) / n
local sum = f(a) + f(b)
for i = 1, n-1 do
local x = a + i * h
sum = sum + (i % 2 == 0 and 2 or 4) * f(x)
end
return sum * h / 3
end
-- Приближенные методы дифференцирования
-- Метод конечных разностей (центральные разности)
function mathematic.differentiate(f, x, h)
return (f(x + h) - f(x - h)) / (2 * h)
end
-- Ряды и последовательности
-- Арифметическая прогрессия
function mathematic.arithmetic_series(a1, d, n)
return n / 2 * (2 * a1 + (n - 1) * d)
end
-- Геометрическая прогрессия
function mathematic.geometric_series(a1, r, n)
if r == 1 then
return a1 * n
else
return a1 * (1 - mathematic.power(r, n)) / (1 - r)
end
end
-- =======================
-- Экспоненциальные и логарифмические функции
-- =======================
-- Возведение в произвольную степень
function mathematic.power_real(a, b)
if a <= 0 then
error("Base must be positive for real exponents")
end
return mathematic.exp(b * mathematic.ln(a))
end
-- Логарифмы с произвольным основанием
function mathematic.log_base(a, base)
return mathematic.ln(a) / mathematic.ln(base)
end
-- Комплексная экспонента (упрощенная реализация, возвращает таблицу {real, imag})
function mathematic.exp_complex(a, b)
return {
real = mathematic.exp(a) * mathematic.cos(b),
imag = mathematic.exp(a) * mathematic.sin(b)
}
end
-- =======================
-- Комбинаторика
-- =======================
-- Перестановки (nPk)
function mathematic.permutation(n, k)
if k > n then
return 0
end
return mathematic.factorial(n) / mathematic.factorial(n - k)
end
-- Сочетания (nCk)
function mathematic.combination(n, k)
if k > n then
return 0
end
return mathematic.factorial(n) / (mathematic.factorial(k) * mathematic.factorial(n - k))
end
-- Разбиения множества (без учета порядка)
function mathematic.partition(n, k)
if k == 0 or k > n then
return 0
elseif k == 1 or k == n then
return 1
else
return mathematic.partition(n-1, k-1) + k * mathematic.partition(n-1, k)
end
end
-- Бином Ньютона (расширение биномиальных коэффициентов)
function mathematic.binomial_expansion(a, b, n)
local terms = {}
for k = 0, n do
terms[k+1] = mathematic.combination(n, k) * mathematic.power(a, n - k) * mathematic.power(b, k)
end
return terms
end
-- =======================
-- Статистика и теория вероятностей
-- =======================
-- Основные статистические меры
-- Среднее арифметическое
function mathematic.mean(data)
local sum = 0
for _, v in ipairs(data) do
sum = sum + v
end
return sum / #data
end
-- Медиана
function mathematic.median(data)
table.sort(data)
local n = #data
if n % 2 == 1 then
return data[(n + 1) / 2]
else
return (data[n / 2] + data[n / 2 + 1]) / 2
end
end
-- Мода
function mathematic.mode(data)
local frequency = {}
local max_freq = 0
local modes = {}
for _, v in ipairs(data) do
frequency[v] = (frequency[v] or 0) + 1
if frequency[v] > max_freq then
max_freq = frequency[v]
end
end
for k, v in pairs(frequency) do
if v == max_freq then
table.insert(modes, k)
end
end
return modes
end
-- Дисперсия
function mathematic.variance(data)
local m = mathematic.mean(data)
local sum_sq = 0
for _, v in ipairs(data) do
sum_sq = sum_sq + mathematic.pow(v - m, 2)
end
return sum_sq / (#data - 1)
end
-- Стандартное отклонение
function mathematic.std_deviation(data)
return mathematic.sqrt(mathematic.variance(data))
end
-- Функции распределения
-- Нормальное распределение (плотность вероятности)
function mathematic.normal_pdf(x, mean, std_dev)
return (1 / (mathematic.sqrt(2 * mathematic.pi) * std_dev)) * mathematic.exp(-mathematic.pow(x - mean, 2) / (2 * mathematic.pow(std_dev, 2)))
end
-- Биномиальное распределение (вероятность)
function mathematic.binomial_pmf(k, n, p)
return mathematic.combination(n, k) * mathematic.power(p, k) * mathematic.power(1 - p, n - k)
end
-- Пуассоновское распределение (вероятность)
function mathematic.poisson_pmf(k, lambda)
return (mathematic.power(lambda, k) * mathematic.exp(-lambda)) / mathematic.factorial(k)
end
-- Тестирование гипотез
-- t-тест (независимые выборки, упрощенная версия)
function mathematic.t_test(sample1, sample2)
local mean1 = mathematic.mean(sample1)
local mean2 = mathematic.mean(sample2)
local var1 = mathematic.variance(sample1)
local var2 = mathematic.variance(sample2)
local n1 = #sample1
local n2 = #sample2
local se = mathematic.sqrt(var1 / n1 + var2 / n2)
return (mean1 - mean2) / se
end
-- =======================
-- Геометрические функции
-- =======================
-- Вычисление площади многоугольника по координатам вершин (алгоритм Гаусса)
function mathematic.polygon_area(vertices)
local area = 0
local n = #vertices
for i = 1, n do
local j = (i % n) + 1
area = area + vertices[i].x * vertices[j].y - vertices[j].x * vertices[i].y
end
return mathematic.abs(area) / 2
end
-- Вычисление объема прямоугольного параллелепипеда
function mathematic.rectangular_prism_volume(length, width, height)
return length * width * height
end
-- Переход между декартовой и полярной системами координат
-- Декартовы координаты в полярные
function mathematic.cartesian_to_polar(x, y)
return mathematic.sqrt(x^2 + y^2), mathematic.atan(y / x)
end
-- Полярные координаты в декартовы
function mathematic.polar_to_cartesian(r, theta)
return r * mathematic.cos(theta), r * mathematic.sin(theta)
end
-- =======================
-- Численные методы
-- =======================
-- Лагранжевы полиномы
function mathematic.lagrange_interpolation(x, y, xi)
local n = #x
local result = 0
for i = 1, n do
local term = y[i]
for j = 1, n do
if j ~= i then
term = term * (xi - x[j]) / (x[i] - x[j])
end
end
result = result + term
end
return result
end
-- Метод наименьших квадратов (линейная регрессия)
function mathematic.least_squares_fit(x, y)
local n = #x
local sum_x = 0
local sum_y = 0
local sum_xy = 0
local sum_xx = 0
for i = 1, n do
sum_x = sum_x + x[i]
sum_y = sum_y + y[i]
sum_xy = sum_xy + x[i] * y[i]
sum_xx = sum_xx + x[i] * x[i]
end
local denominator = n * sum_xx - sum_x * sum_x
if denominator == 0 then
error("Denominator is zero, cannot perform regression")
end
local a = (sum_y * sum_xx - sum_x * sum_xy) / denominator
local b = (n * sum_xy - sum_x * sum_y) / denominator
return a, b
end
-- Градиентный спуск (простой пример для минимизации функции)
function mathematic.gradient_descent(f, df, start, learning_rate, iterations)
local x = start
for i = 1, iterations do
x = x - learning_rate * df(x)
end
return x
end
-- =======================
-- Комплексные числа
-- =======================
-- Операции с комплексными числами
-- Сложение
function mathematic.complex_add(c1, c2)
return { real = c1.real + c2.real, imag = c1.imag + c2.imag }
end
-- Вычитание
function mathematic.complex_sub(c1, c2)
return { real = c1.real - c2.real, imag = c1.imag - c2.imag }
end
-- Умножение
function mathematic.complex_mul(c1, c2)
return {
real = c1.real * c2.real - c1.imag * c2.imag,
imag = c1.real * c2.imag + c1.imag * c2.real
}
end
-- Деление
function mathematic.complex_div(c1, c2)
local denominator = c2.real^2 + c2.imag^2
if denominator == 0 then
error("Division by zero in complex division")
end
return {
real = (c1.real * c2.real + c1.imag * c2.imag) / denominator,
imag = (c1.imag * c2.real - c1.real * c2.imag) / denominator
}
end
-- Модуль комплексного числа
function mathematic.complex_mod(c)
return mathematic.sqrt(c.real^2 + c.imag^2)
end
-- Аргумент комплексного числа
function mathematic.complex_arg(c)
return mathematic.atan(c.imag / c.real)
end
-- Комплексные функции
-- Комплексная экспонента
function mathematic.complex_exp(c)
return {
real = mathematic.exp(c.real) * mathematic.cos(c.imag),
imag = mathematic.exp(c.real) * mathematic.sin(c.imag)
}
end
-- Комплексный синус
function mathematic.complex_sin(c)
return {
real = mathematic.sin(c.real) * mathematic.cosh(c.imag),
imag = mathematic.cos(c.real) * mathematic.sinh(c.imag)
}
end
-- Комплексный косинус
function mathematic.complex_cos(c)
return {
real = mathematic.cos(c.real) * mathematic.cosh(c.imag),
imag = -mathematic.sin(c.real) * mathematic.sinh(c.imag)
}
end
-- =======================
-- Математическая логика и теория множеств
-- =======================
-- Булевы операции
-- Логическое И
function mathematic.boolean_and(a, b)
return a and b
end
-- Логическое ИЛИ
function mathematic.boolean_or(a, b)
return a or b
end
-- Логическое НЕ
function mathematic.boolean_not(a)
return not a
end
-- Множества
-- Объединение множеств
function mathematic.set_union(set1, set2)
local union = {}
local seen = {}
for _, v in ipairs(set1) do
if not seen[v] then
table.insert(union, v)
seen[v] = true
end
end
for _, v in ipairs(set2) do
if not seen[v] then
table.insert(union, v)
seen[v] = true
end
end
return union
end
-- Пересечение множеств
function mathematic.set_intersection(set1, set2)
local intersection = {}
local seen = {}
for _, v in ipairs(set2) do
seen[v] = true
end
for _, v in ipairs(set1) do
if seen[v] then
table.insert(intersection, v)
end
end
return intersection
end
-- Разность множеств
function mathematic.set_difference(set1, set2)
local difference = {}
local seen = {}
for _, v in ipairs(set2) do
seen[v] = true
end
for _, v in ipairs(set1) do
if not seen[v] then
table.insert(difference, v)
end
end
return difference
end
-- =======================
-- Дифференциальные уравнения
-- =======================
-- Решение ОДУ методом Эйлера
function mathematic.euler_method(f, x0, y0, h, n)
local x = x0
local y = y0
local points = { {x, y} }
for i = 1, n do
y = y + h * f(x, y)
x = x + h
table.insert(points, {x, y})
end
return points
end
-- Метод Рунге-Кутты 4-го порядка
function mathematic.runge_kutta_4(f, x0, y0, h, n)
local x = x0
local y = y0
local points = { {x, y} }
for i = 1, n do
local k1 = h * f(x, y)
local k2 = h * f(x + h / 2, y + k1 / 2)
local k3 = h * f(x + h / 2, y + k2 / 2)
local k4 = h * f(x + h, y + k3)
y = y + (k1 + 2 * k2 + 2 * k3 + k4) / 6
x = x + h
table.insert(points, {x, y})
end
return points
end
-- Решение системы дифференциальных уравнений (упрощенная версия)
function mathematic.solve_ode_system(fx, fy, x0, y0, h, n)
local x = x0
local y = y0
local points = { {x, y} }
for i = 1, n do
local k1x = h * fx(x, y)
local k1y = h * fy(x, y)
local k2x = h * fx(x + h/2, y + k1y/2)
local k2y = h * fy(x + h/2, y + k1x/2)
local k3x = h * fx(x + h/2, y + k2y/2)
local k3y = h * fy(x + h/2, y + k2x/2)
local k4x = h * fx(x + h, y + k3y)
local k4y = h * fy(x + h, y + k3x)
y = y + (k1y + 2*k2y + 2*k3y + k4y) / 6
x = x + h
table.insert(points, {x, y})
end
return points
end
-- =======================
-- Функции комплексного анализа
-- =======================
-- Проверка аналитичности функции (упрощенная версия)
function mathematic.is_analytic(f, x, y)
-- Здесь можно использовать критерий Коши-Римана
-- f = u + iv
local h = 1e-5
local u = function(a, b)
return f(a, b).real
end
local v = function(a, b)
return f(a, b).imag
end
local du_dx = mathematic.differentiate(function(a) return u(a, y) end, x, h)
local du_dy = mathematic.differentiate(function(b) return u(x, b) end, y, h)
local dv_dx = mathematic.differentiate(function(a) return v(a, y) end, x, h)
local dv_dy = mathematic.differentiate(function(b) return v(x, b) end, y, h)
return mathematic.abs(du_dx - dv_dy) < 1e-5 and mathematic.abs(du_dy + dv_dx) < 1e-5
end
-- Интегралы в комплексной плоскости (упрощенная версия)
function mathematic.complex_integral(f, path, steps)
-- path: функция возвращающая координаты x(t), y(t) для t в [0,1]
local integral = { real = 0, imag = 0 }
local prev = path(0)
for i = 1, steps do
local t = i / steps
local current = path(t)
local dx = current.x - prev.x
local dy = current.y - prev.y
local dz = { real = dx, imag = dy }
local f_z = f(current.x, current.y)
integral.real = integral.real + (f_z.real * dz.real - f_z.imag * dz.imag)
integral.imag = integral.imag + (f_z.real * dz.imag + f_z.imag * dz.real)
prev = current
end
return integral
end
-- =======================
-- Матричные функции
-- =======================
-- Экспонента матрицы (приближенная реализация с использованием ряда Тейлора)
function mathematic.matrix_exp(m)
local n = #m
local result = mathematic.matrix_identity(n)
local term = mathematic.matrix_identity(n)
for k = 1, 20 do -- Ограничение числа членов ряда
term = mathematic.matrix_multiply(term, m)
for i = 1, n do
for j = 1, n do
term[i][j] = term[i][j] / k
end
end
result = mathematic.matrix_add(result, term)
end
return result
end
-- Логарифм матрицы (приближенная реализация, предполагается, что матрица близка к единичной)
function mathematic.matrix_log(m)
local n = #m
local identity = mathematic.matrix_identity(n)
local diff = mathematic.matrix_subtract(m, identity)
local term = mathematic.matrix_copy(diff)
local result = mathematic.matrix_copy(diff)
for k = 2, 20 do
local power = mathematic.matrix_multiply(diff, mathematic.matrix_copy(result))
for i = 1, n do
for j = 1, n do
power[i][j] = power[i][j] / k
end
end
result = mathematic.matrix_add(result, power)
end
return result
end
-- Определение единичной матрицы
function mathematic.matrix_identity(n)
local identity = {}
for i = 1, n do
identity[i] = {}
for j = 1, n do
identity[i][j] = (i == j) and 1 or 0
end
end
return identity
end
-- Вычитание двух матриц
function mathematic.matrix_subtract(m1, m2)
local rows = #m1
local cols = #m1[1]
if rows ~= #m2 or cols ~= #m2[1] then
error("Matrices must have the same dimensions")
end
local result = {}
for i = 1, rows do
result[i] = {}
for j = 1, cols do
result[i][j] = m1[i][j] - m2[i][j]
end
end
return result
end
-- =======================
-- Экономико-математические функции
-- =======================
-- Простые проценты
function mathematic.simple_interest(principal, rate, time)
return principal * (1 + rate * time)
end
-- Сложные проценты
function mathematic.compound_interest(principal, rate, times, time)
return principal * mathematic.power(1 + rate / times, times * time)
end
-- Амортизация методом равных платежей (аннуитетный)
function mathematic.amortization_annuity(principal, rate, periods)
local payment = (principal * rate) / (1 - mathematic.power(1 + rate, -periods))
return payment
end
-- Линейное программирование (упрощенный пример: максимизация c^T x при Ax ≤ b)
function mathematic.linear_programming(c, A, b)
-- Реализация полного метода симплекс невозможно в рамках этого модуля
-- Предлагается использовать готовые библиотеки или реализовать симплекс-метод отдельно
error("Linear programming solver is not implemented")
end
-- Возвращение таблицы библиотеки
return mathematic
Пояснения и Дополнения
-
Метод Ньютона для нахождения корней:
- Реализован метод
solve_quadratic для квадратных уравнений и solve_cubic для кубических. Для произвольных функций рекомендуется реализовать общий метод Ньютона, который можно добавить аналогично.
-
Полиномиальные функции:
- Функция
evaluate_polynomial позволяет вычислять значения полиномов различных степеней.
- Функция
factorize_polynomial реализует простой метод факторизации полиномов с рациональными корнями.
-
Линейная алгебра:
- Добавлены операции с векторами и матрицами, включая складывание, умножение, транспонирование, вычисление определителя и обратной матрицы.
- Реализованы методы решения систем линейных уравнений методом Гаусса и Крамера.
-
Тригонометрические функции:
- Добавлены дополнительные функции: котангенс (
cot), секанс (sec), косеканс (csc), а также гиперболические функции и их обратные.
- Включены примеры многоугольных формул и тождественных преобразований.
-
Специальные функции:
- Реализованы приближенные версии функций Бесселя, гамма-функции и функции Римана Зета.
-
Анализ и высшая математика:
- Включены численные методы интегрирования (метод трапеций и Симпсона) и дифференцирования.
- Реализованы примеры числовых рядов и простые методы дифференциального анализа.
-
Экспоненциальные и логарифмические функции:
- Дополнены функции для возведения в произвольную степень и работа с комплексными экспонентами.
-
Комбинаторика:
- Добавлены функции для вычисления перестановок, сочетаний, разбиений множества и биномиальных коэффициентов.
-
Статистика и теория вероятностей:
- Реализованы основные статистические меры, функции распределения и примеры тестов гипотез.
-
Геометрические функции:
- Включены вычисления площадей многоугольников, объемов фигур и переходы между системами координат.
-
Численные методы:
Заключение
Этот расширенный модуль mathematic.lua покрывает широкий спектр математических функций и методов. Некоторые функции (например, решения нелинейных и дифференциальных уравнений, специальные функции и матричные операции) реализованы приближенно и могут требовать доработки для повышения точности и производительности. Рекомендуется протестировать каждую функцию отдельно и при необходимости оптимизировать их под ваши конкретные задачи.
Кроме того, для некоторых сложных операций, таких как решение систем линейного программирования, может быть предпочтительнее использовать специализированные библиотеки или модули, так как их реализация требует значительных усилий и глубокого понимания методов.
Если у вас есть конкретные вопросы или понадобится помощь с определёнными функциями, не стесняйтесь обращаться!