Created
July 13, 2024 20:03
-
-
Save Chriscbr/5c62b219ba5dc8664a4acdd77a526638 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Goal: try to find a functions f(x) and g(x) such that f(g(x)) is increasing and g(f(x)) is decreasing. | |
(This program does not solve the puzzle.) | |
""" | |
import math | |
fns = [ | |
(lambda x: 0, "0"), | |
(lambda x: 1, "1"), | |
(lambda x: x, "x"), | |
(lambda x: x + 1, "x + 1"), | |
(lambda x: -x, "-x"), | |
(lambda x: 1 - x, "1 - x"), | |
(lambda x: abs(x), "abs(x)"), | |
(lambda x: x ** 2, "x^2"), | |
(lambda x: x ** 3, "x^3"), | |
(lambda x: 2 ** x, "2^x"), | |
(lambda x: 1 / x, "1/x"), | |
(lambda x: 1 / x, "1/x"), | |
(lambda x: x ** 0.5, "x^0.5"), | |
(lambda x: math.sqrt(x), "sqrt(x)"), | |
(lambda x: math.cbrt(x), "cbrt(x)"), | |
(lambda x: math.log(x), "log(x)"), | |
(lambda x: math.exp(x), "exp(x)"), | |
(lambda x: 1 if x > 0 else -1 if x < -1 else 0, "sgn(x)"), | |
(lambda x: x ** 2 if x >= 0 else -(x ** 2), "x^2 if x >= 0 else -(x^2)"), | |
(lambda x: -(x ** 0.5) if x >= 0 else (-x) ** 0.5, "-(x^0.5) if x >= 0 else (-x)^0.5"), | |
] | |
xs = [-2, -1, 0, 1, 2] | |
def is_increasing(xs): | |
for x in xs: | |
if x is None or isinstance(x, complex) or math.isnan(x): | |
return False | |
for i in range(len(xs) - 1): | |
if xs[i] >= xs[i + 1]: | |
return False | |
return True | |
def is_decreasing(xs): | |
for x in xs: | |
if x is None or isinstance(x, complex) or math.isnan(x): | |
return False | |
for i in range(len(xs) - 1): | |
if xs[i] <= xs[i + 1]: | |
return False | |
return True | |
# g1 = fns[-2][0] | |
# g2 = fns[-1][0] | |
# ys = [] | |
# for x in xs: | |
# y = g1(g2(x)) | |
# ys.append(y) | |
# print(ys) | |
# ys = [] | |
# for x in xs: | |
# y = g2(g1(x)) | |
# ys.append(y) | |
# print(ys) | |
for f1 in fns: | |
for f2 in fns: | |
ys1 = [] | |
for x in xs: | |
try: | |
y = f1[0](f2[0](x)) | |
ys1.append(y) | |
except Exception as e: | |
ys1.append(None) # ignore errors | |
ys2 = [] | |
for x in xs: | |
try: | |
y = f2[0](f1[0](x)) | |
ys2.append(y) | |
except Exception as e: | |
ys2.append(None) # ignore errors | |
if is_increasing(ys1) and is_decreasing(ys2): | |
print(f"f(x) = {f1[1]}, g(x) = {f2[1]}") | |
print(ys1) | |
print(ys2) | |
if is_decreasing(ys1) and is_increasing(ys2): | |
print(f"f(x) = {f1[1]}, g(x) = {f2[1]}") | |
print(ys1) | |
print(ys2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment