Skip to content

Instantly share code, notes, and snippets.

@iuriguilherme
Created November 27, 2022 23:11
Show Gist options
  • Save iuriguilherme/a9ca8c5dc622a8f4f7ad1cd299bace16 to your computer and use it in GitHub Desktop.
Save iuriguilherme/a9ca8c5dc622a8f4f7ad1cd299bace16 to your computer and use it in GitHub Desktop.
"""
Finding the solution for x ^ (x + 1) = (x + 1) ^ x
python main.py m start stop step dps
pip install matplotlib mpmath numpy sympy
Supposed truth values:
2.271823903
2.293053068
2.293166284
2.293166287
2.293166287411861
2.293166287411861016742710082
"""
import collections
import colorama
import decimal
import fractions
import logging
import mpmath
import numpy
import sympy
import sys
import time
import typing
from matplotlib import pyplot
try:
log_level: str = str(sys.argv[1]).upper()
except (IndexError, ValueError):
log_level: str = 'DEBUG'
logging.basicConfig(level = log_level.upper())
logger = logging.getLogger(__name__)
def parse_args(*args, **kwargs) -> dict:
"""parse cli args"""
cast = kwargs.get('cast', float_wrapper)
kwargs['cast']: object = cast
try:
kwargs['start']: object = cast(kwargs.get('start', args[2]))
except:
# ~ kwargs['start']: float = 2.293166283
# ~ kwargs['start']: float = 2.29316628737135
# ~ kwargs['start']: float = 2.293166287411859
kwargs['start']: float = 2.293166287411861016742710081
try:
kwargs['stop']: object = cast(kwargs.get('stop', args[3]))
except:
# ~ kwargs['stop']: float = 2.293166288
# ~ kwargs['stop']: float = 2.29316628743975
# ~ kwargs['stop']: float = 2.293166287411862
kwargs['stop']: float = 2.293166287411861016742710083
try:
kwargs['step']: object = cast(kwargs.get('step', args[4]))
except:
# ~ kwargs['step']: float = 1e-15
kwargs['step']: float = 1e-30
try:
kwargs['dps']: int = max(1, int(kwargs.get('dps', args[5])))
except:
# ~ kwargs['dps']: int = 15
kwargs['dps']: int = 15
try:
kwargs['maxn']: int = max(1, int(kwargs.get('maxn', args[6])))
except:
kwargs['maxn']: int = 30
try:
kwargs['sleep']: int = max(1, int(kwargs.get('sleep', args[7])))
except:
# ~ kwargs['sleep']: int = 15
# ~ kwargs['sleep']: int = 6
kwargs['sleep']: int = 3
return kwargs
def colorize(number: float) -> str:
"""Returns a color version of a string defined in a map"""
try:
color_map: dict = {
'0': (colorama.Fore.RED, colorama.Back.BLACK),
'1': (colorama.Fore.GREEN, colorama.Back.BLACK),
'2': (colorama.Fore.YELLOW, colorama.Back.BLACK),
'3': (colorama.Fore.BLUE, colorama.Back.BLACK),
'4': (colorama.Fore.MAGENTA, colorama.Back.BLACK),
'5': (colorama.Fore.CYAN, colorama.Back.BLACK),
'6': (colorama.Fore.RED, colorama.Back.BLACK),
'7': (colorama.Fore.GREEN, colorama.Back.BLACK),
'8': (colorama.Fore.YELLOW, colorama.Back.BLACK),
'9': (colorama.Fore.BLUE, colorama.Back.BLACK),
'.': (colorama.Fore.MAGENTA, colorama.Back.BLACK),
'-': (colorama.Fore.CYAN, colorama.Back.BLACK),
}
return ''.join([''.join([
colorama.Style.BRIGHT,
color_map[n][0],
color_map[n][1],
n,
colorama.Style.RESET_ALL,
]) for n in f"{float(number):.15f}"])
except:
raise
def float_wrapper(*args, **kwargs) -> float:
"""float without kwargs"""
try:
return float(*args)
except:
raise
def mpf_wrapper(*args, **kwargs) -> mpmath.mpf:
"""mpf without kwargs"""
try:
return mpmath.mpf(*args)
except:
raise
def Float_wrapper(*args, **kwargs) -> sympy.Float:
"""Float without kwargs"""
try:
return sympy.Float(*args)
except:
raise
def N_wrapper(*args, **kwargs) -> sympy.N:
"""N without unused kwargs"""
try:
return sympy.N(*args, **{
'maxn': kwargs.get('maxn'),
'chop': kwargs.get('chop'),
})
except:
raise
def pow_wrapper(*args, **kwargs) -> float:
return pow(*args)
def mpow_wrapper(*args, **kwargs) -> float:
return mpmath.pow(*args)
def rxy(
start: object = 0.0,
stop: object = 1.0,
step: object = 0.1,
cast: object = float_wrapper,
calc: object = float_wrapper,
**kwargs,
) -> typing.Tuple[numpy.arange, numpy.array, numpy.array]:
"""Returns all points as numpy arrays"""
try:
r, x, y = None, None, None
while r is None and x is None and y is None:
try:
r: numpy.arange = numpy.arange(
cast(start),
cast(stop),
cast(step)
)
x: numpy.array = numpy.array([
calc(cast(n) ** cast(cast(n) + 1), **kwargs) \
for n in r
])
y: numpy.array = numpy.array([
calc(cast(cast(n) + 1) ** cast(n), **kwargs) \
for n in r
])
return (r, x, y)
except (ValueError, MemoryError):
step = step * 10
logging.warning(f"step was too low, it is now {step}")
except:
raise
except:
raise
def write(
start: object = 0.0,
stop: object = 1.0,
step: object = 0.1,
cast: object = float_wrapper,
calc: object = float_wrapper,
powf: object = pow_wrapper,
**kwargs,
) -> list[tuple]:
"""write solution to file"""
try:
l: list = []
s: bool = False
while not s:
try:
for n in numpy.arange(cast(start), cast(stop), cast(step)):
if \
calc(powf(cast(n), cast(cast(n) + 1)), **kwargs) \
== \
calc(powf(cast(cast(n) + 1), cast(n)), **kwargs) \
:
print("solved!")
l.append((True, n))
with open('solutions.txt', 'a') as _file:
_file.write(f"solved for n = {n}")
else:
l.append((False, n))
return l
except MemoryError:
step = step * 10
logging.warning(f"step was too low, it is now {step}")
except:
raise
except:
raise
def fiter(
start: object = 0.0,
stop: object = 1.0,
step: object = 0.1,
cast: object = float_wrapper,
calc: object = float_wrapper,
**kwargs,
) -> list[tuple]:
"""Real number range iteration"""
try:
l: list = []
r, x, y = rxy(start, stop, step, **kwargs)
for i, n in enumerate(r):
print(f"""\
x = {colorize(cast(n))}, \
f1(x) = {colorize(cast(y[i]))}, \
f2(x) = {colorize(cast(x[i]))}, \
f3(x) = {colorize(
calc(cast(cast(y[i]) - cast(x[i])),
**kwargs,
))}, \
f4(x) = \
{colorize(
calc(cast(cast(cast(y[i]) + cast(x[i])) / 2) - cast(x[i]),
**kwargs,
))}\
""")
l.append((calc(x[i]) == calc(y[i]), calc(cast(y[i]) - cast(x[i]))))
return l
except:
raise
def crossplot(
start: object = 0.0,
stop: object = 1.0,
step: object = 0.1,
**kwargs,
) -> list[tuple]:
"""Ploting lines to find the cross intersection"""
try:
s: bool = False
while not s:
try:
r, x, y = rxy(start, stop, step, **kwargs)
l: list = [(True, z) for z in numpy.intersect1d(x, y)]
# ~ pyplot.plot(r)
del(r)
pyplot.plot(x)
del(x)
pyplot.plot(y)
del(y)
pyplot.show()
pyplot.clf()
return l
except (MemoryError, TclError):
kwargs['step'] = kwargs.get('step') * 10
logging.warning(f"""step was too low, it is now \
{kwargs.get('step')}""")
except:
raise
except:
raise
def counting(
function: object = fiter,
start: object = 0.0,
stop: object = 1.0,
step: object = 0.1,
cast: object = float_wrapper,
calc: object = float_wrapper,
**kwargs,
) -> str:
"""Count solutions"""
try:
ret: list = []
c: collections.Counter = collections.Counter([i[1] \
for i in function(
start = cast(start),
stop = cast(stop),
step = cast(step),
cast = cast,
calc = calc,
**kwargs,
) \
if i[0]
])
ret.append(f"""Total de soluções encontradas com {repr(function)}: \
{c.total()}""")
try:
ret.append(f"Número mais próximo: {c.most_common()[0]}")
except IndexError:
pass
return '\n'.join(ret)
except:
raise
def counting_float(*args, **kwargs) -> None:
"""Python builtin floats"""
print(counting(
calc = float_wrapper,
**parse_args(*args, cast = float),
**kwargs,
))
def counting_decimal(*args, **kwargs) -> None:
"""decimal.decimal.Decimal"""
print(counting(
calc = float_wrapper,
**parse_args(*args, cast = decimal.Decimal),
**kwargs,
))
def counting_fraction(*args, **kwargs) -> None:
"""fractions.Fraction"""
print(counting(
calc = float_wrapper,
**parse_args(*args, cast = fractions.Fraction),
**kwargs,
))
def counting_mpf(*args, **kwargs) -> None:
"""mpmath.mpf"""
print(counting(
calc = float_wrapper,
powf = mpow_wrapper,
**parse_args(*args, cast = mpmath.mpf),
**kwargs,
))
def counting_sym(*args, **kwargs) -> None:
"""sympy.N"""
print(counting(
calc = N_wrapper,
powf = mpow_wrapper,
**parse_args(*args, cast = Float_wrapper),
**kwargs,
))
funs: list = [
#counting_float,
#counting_decimal,
#counting_fraction,
counting_mpf,
#counting_sym, #FIXME not working
]
subfuns: list = [
#write,
fiter,
# ~ crossplot,
]
print(f"cli args: *enumerate(sys.argv)")
for fun in funs:
for subfun in subfuns:
try:
kwargs: dict = parse_args(*sys.argv)
with mpmath.workdps(kwargs.get('dps', 15)):
print(f"""\
Tempo de execução para máximo de {kwargs.get('maxn')} iterações\n\
com precisão decimal máxima de {kwargs.get('dps')}\n\
para x <= {kwargs.get('start')} \
e x >= {kwargs.get('stop')} \
a cada {kwargs.get('step')}\n\
em f1(x) = (x + 1) ^ x\n\
f2(x) = x ^ (x + 1)\n\
f3(x) = f1(x) - f2(x)\n\
f4(x) = {{[f1(x) + f2(x)] / 2}} - f2(x)\n\
para {repr(fun)}: {mpmath.timing(fun, *sys.argv, **{'function': subfun})}\n\
Próxima função em {kwargs.get('sleep')} segundos...""")
time.sleep(kwargs.get('sleep'))
except Exception as e:
logging.exception(e)
print(f"Exceção em {repr(subfun)}: {repr(e)}")
print("Fim.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment