Files
genetic-algorithms/lab4/gp/ops.py
2025-11-04 15:02:02 +03:00

52 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import math
from .operation import Operation
# Унарные операции
NEG = Operation("-", 1, lambda x: -x[0])
SIN = Operation("sin", 1, lambda x: math.sin(x[0]))
COS = Operation("cos", 1, lambda x: math.cos(x[0]))
def _safe_exp(a: float) -> float:
if a < 700.0:
if a > -700.0:
return math.exp(a)
return 0.0
else:
return float("inf")
EXP = Operation("exp", 1, lambda x: _safe_exp(x[0]))
# Бинарные операции
ADD = Operation("+", 2, lambda x: x[0] + x[1])
SUB = Operation("-", 2, lambda x: x[0] - x[1])
MUL = Operation("*", 2, lambda x: x[0] * x[1])
DIV = Operation("/", 2, lambda x: x[0] / x[1] if x[1] != 0 else float("inf"))
def safe_pow(a, b):
# 0 в отрицательной степени
if abs(a) <= 1e-12 and b < 0:
return float("inf")
# отрицательное основание при нецелой степени
if a < 0 and abs(b - round(b)) > 1e-12:
return float("inf")
# грубое насыщение (настрой пороги под задачу)
if abs(a) > 1 and b > 20:
return float("inf")
if abs(a) < 1 and b < -20:
return float("inf")
try:
return a**b
except (OverflowError, ValueError):
return float("inf")
POW = Operation("^", 2, lambda x: safe_pow(x[0], x[1]))
# Все операции в либе
ALL = (NEG, SIN, COS, EXP, ADD, SUB, MUL, DIV, POW)