使用 Python3 生成分形图,在编程中领略分形几何之美

大家好!欢迎来到我们第二期的代码滤镜。不关心实现细节,每天一个炫酷好玩儿的项目演示,激发编程兴趣,扩展技术视野。


今日实验主题是: 用 Python3 生成分形图片

鹅厂微信端把视频压缩成

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
生成分形案是利用数学公式和计算机程序来实现的,以下是使用Python语言生成分形案的一些方法: 1. Mandelbrot集合:Mandelbrot集合是一种著名的分形案,可以通过使用Python的matplotlib库绘制出来。具体实现方法可以参考以下代码: ```python import numpy as np import matplotlib.pyplot as plt def mandelbrot(Re, Im, max_iter): c = complex(Re, Im) z = 0.0j for i in range(max_iter): z = z*z + c if(z.real*z.real + z.imag*z.imag) >= 4: return i return max_iter def mandelbrot_set(xmin, xmax, ymin, ymax, width, height, max_iter): r1 = np.linspace(xmin, xmax, width) r2 = np.linspace(ymin, ymax, height) return [[mandelbrot(r, i, max_iter) for r in r1] for i in r2] plt.imshow(mandelbrot_set(-2.0, 0.5, -1.25, 1.25, 500, 500, 100), cmap='hot', interpolation='nearest') plt.show() ``` 2. Julia集合:Julia集合是另一种著名的分形案,也可以使用Python的matplotlib库绘制出来。具体实现方法可以参考以下代码: ```python import numpy as np import matplotlib.pyplot as plt def julia(Re, Im, max_iter): c = complex(-0.7, 0.27015) z = complex(Re, Im) for i in range(max_iter): z = z*z + c if(z.real*z.real + z.imag*z.imag) >= 4: return i return max_iter def julia_set(xmin, xmax, ymin, ymax, width, height, max_iter): r1 = np.linspace(xmin, xmax, width) r2 = np.linspace(ymin, ymax, height) return [[julia(r, i, max_iter) for r in r1] for i in r2] plt.imshow(julia_set(-1.5, 1.5, -1.5, 1.5, 500, 500, 100), cmap='hot', interpolation='nearest') plt.show() ``` 3. Barnsley fern:Barnsley fern是一种常见的分形植物案,可以通过使用Python的turtle库绘制出来。具体实现方法可以参考以下代码: ```python import turtle import random def barnsley_fern(n): x, y = 0, 0 for i in range(n): r = random.random() if r < 0.01: x, y = 0, 0.16*y elif r < 0.86: x, y = 0.85*x + 0.04*y, -0.04*x + 0.85*y + 1.6 elif r < 0.93: x, y = 0.2*x - 0.26*y, 0.23*x + 0.22*y + 1.6 else: x, y = -0.15*x + 0.28*y, 0.26*x + 0.24*y + 0.44 turtle.penup() turtle.goto(85*x, 57*y-275) turtle.pendown() turtle.dot(2, 'green') turtle.speed('fastest') turtle.hideturtle() barnsley_fern(10000) turtle.done() ``` 以上是几种常见的生成分形案的方法,欢迎尝试!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值