python - 我的 Tetration(复数)函数必须更好地矢量化(Python)

标签 python numpy math vectorization complex-numbers

Inspired by 3blue1brown我正在尝试绘制 Tetration 的逃逸(发散)图使用 Python 运行函数 –– 类似于这个漂亮的图形 on Wikipedia .

def tetration_com(base, tol=10**-15, max_step=10**6):
  # returns t, the infinite tetration of base.
  # if t does not converge, the function returns an escape value, aka how fast it diverges..

  t = 1.0
  step = 0
  escape = None
  ln_base = cmath.log(base)

  t_last = 0
  try:
    while(abs(t - t_last) > tol):
      if(step > max_step):
        raise OverflowError
      t_last = t
      t = cmath.exp(ln_base*t)   # [ base^t == e^(ln(base)*t) ]
      step += 1

  except(OverflowError):
    t = None
    escape = 1000/step
    # the escape value is is inversely related to the number of steps it took
    # us to diverge to infinity

  return t, escape

我正在尝试使其与网格一起使用,以便在 x-y 平面上绘制逃逸图。 Python 不喜欢输出是 2 个未打包的变量(限制或转义)——我绝对可以通过拆分为两个函数来解决这个问题。

但另一个问题是复杂数学运算(cmath.log、cmath.exp)仅适用于标量......

我尝试向量化该函数:

nx, ny = 700, 500
x, y = np.linspace(-3.5, 3.5, nx), np.linspace(-2.5, 2.5, ny)
xv, yv = np.meshgrid(x, y)

tetration_vec = np.vectorize(tetration_com)
t, escape = tetration_vec(xv + yv*1j, max_step=500)

但它会永远运行。

关于如何处理复杂数学运算和向量化有什么建议吗?

最佳答案

以下是我最终如何绘制我的逃生图:

def tetration_com(base, tol=10**-15, max_step=10**6, max_val=10**2):
  # returns t, the infinite tetration of base.
  # if t does not converge, the function returns an escape value
  # aka how fast it diverges..

  t = 1.0
  step = 0
  escape = None

  t_last = 0
  try:
    while(abs(t - t_last) > tol):
      if(step > max_step or abs(t) > max_val):
        raise OverflowError
      t_last = t
      t = pow(base, t)
      step += 1
  except(OverflowError):
    t = None
    escape = 1000/step
    # the escape value is is inversely related to the number of steps it took
    # us to diverge to infinity

  return t, escape

矢量化辅助函数:

def tetra_graph_escape(real, imag, tol=10**-15, max_step=10**3, max_val=10**2):
  return np.array([np.array([tetration_com(r + im*1j, tol=tol, max_step=max_step, max_val=max_val)[1]
                             for im in imag]) for r in real])

绘图:

# graph our escape:
nx, ny = 700, 500
x, y = np.linspace(-3.5, 3.5, nx), np.linspace(-2.5, 2.5, ny)

val, escape = tetra_graph_conv(x, y), tetra_graph_escape(x, y)

import matplotlib.pyplot as plt

for r in range(len(escape)):
  for c in range(len(escape[0])):
    if escape[r][c] is None:
      escape[r][c] = -100

escape[460][250]

plt.contour(escape)

四次逃逸的等高线图:

img

关于python - 我的 Tetration(复数)函数必须更好地矢量化(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61921444/

相关文章:

python - 正则表达式组遇到问题

python - 在 Python 中实现链表

python - 当我输入用户名时,未显示 "good job"

Python 对数函数

python - 在 python 中创建交互矩阵

numpy - 当所有值为 NaN 和字符串时 nanpercentile 出现错误

c++ - 从 double 到 unsigned int 的转换

mysql - 如何计算每个订单订购的平均服务以及用户的唯一引用? (MySQL)

.net - 在 VB.Net 中进行未经检查的整数加法的最快方法?

python - 当元素包含 numpy 数组时,无法测试 python 列表元素成员资格