o1-mini-2024-09-12· OpenAI
WildChat-4.8M (AI2)
Untitled conversation
- User
-- mathematic.lua local mathematic = {} -- ======================= -- Константы -- ======================= -- Приближение числа пи с использованием ряда Нилаканта (быстрее сходится, чем ряд Лейбница) local function calculate_pi(iterations) local pi = 3 local sign = 1 local denominator = 2 for i = 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 i = 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] для улучшения сходимости ряда while x > mathematic.pi do x = x - 2 * mathematic.pi end while x < -mathematic.pi do 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] для улучшения сходимости ряда while x > mathematic.pi do x = x - 2 * mathematic.pi end while x < -mathematic.pi do 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 if mathematic.sin(x) > 0 then return mathematic.infinity else return -mathematic.infinity end end return mathematic.sin(x) / cosx 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 end if x == -1 then return -mathematic.pi / 2 end -- Начальное приближение local guess = x -- Метод Ньютона for i = 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 i = 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 = (sin(x)/cos(x)) - a = tan(x) - a -- f' = (cos(x)^2 + sin(x)^2) / cos(x)^2 = 1 / cos(x)^2 local f_derivative = 1 / mathematic.power(cosine, 2) 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.circle_area(radius) return mathematic.pi * mathematic.power(radius, 2) end -- Вычисление длины окружности function mathematic.circle_circumference(radius) return 2 * mathematic.pi * radius end -- Вычисление площади прямоугольника function mathematic.rectangle_area(length, width) return length * width end -- Вычисление периметра прямоугольника function mathematic.rectangle_perimeter(length, width) return 2 * (length + width) end -- Вычисление площади треугольника function mathematic.triangle_area(base, height) return 0.5 * base * height end -- ======================= -- Дополнительные математические функции -- ======================= -- Вычисление натурального логарифма с использованием ряда Тейлора (Махаспур бин Хусейн формула) function mathematic.ln(x) if x <= 0 then error("Natural logarithm undefined for non-positive values") end -- Преобразуем x в (1 + y), где |y| < 1 local y = (x - 1) / (x + 1) local y2 = y * y local term = y local sum = 0 local n = 1 while mathematic.abs(term) > 1e-10 do sum = sum + term / n term = term * y2 n = n + 2 end return 2 * sum end -- Вычисление логарифма по основанию 'base' function mathematic.log(a, base) if a <= 0 or base <= 0 or base == 1 then error("Logarithm undefined for these input values") end return mathematic.ln(a) / mathematic.ln(base) end -- Вычисление экспоненты с использованием ряда Тейлора function mathematic.exp(x) local sum = 1 -- Первый член ряда local term = 1 local n = 1 while mathematic.abs(term) > 1e-10 do term = mathematic.power(x, n) / mathematic.factorial(n) sum = sum + term n = n + 1 end return sum end -- Округление числа 'num' до 'decimal_places' знаков после запятой function mathematic.round(num, decimal_places) decimal_places = decimal_places or 0 local multiplier = mathematic.power(10, decimal_places) return mathematic.floor(num * multiplier + 0.5) / multiplier end -- Возвращение таблицы библиотеки return mathematic - Assistant