python绘制3d机械图_如何在python中将3D功能绘制为2D色彩图?

boffi@debian:~/Documents/tmp$ cat grid.py

import numpy as np

def z(x,y):

return np.sin(np.sqrt(x*x+y*y))

x = np.linspace(-1,1,11)

y = np.linspace(-2,2,21)

# naive

Z0 = np.zeros((len(y), len(x)))

for i, X in enumerate(x):

for j, Y in enumerate(y):

Z0[j,i] = z(X,Y)

# trampoline on a double list comprehension,

# it is possibly faster, sure it uses more memory

Z1 = np.array([[z(X,Y) for X in x] for Y in y])

# numpy has meshgrid,

# meshgrid uses twice memory as the result matrix but

# if used _correctly_ it's FAST

X, Y = np.meshgrid(x, y)

# numpy can avoid you explicit looping,

# but if you are so inclined...

Z2 = np.zeros((len(y), len(x)))

for r in range(len(y)):

for c in range(len(x)):

Z2[r, c] = z(X[r, c], Y[r, c])

# numpy has ufuncs, and

# t h i s i s t h e w a y t o g o

Z3 = z(X, Y)

# numpy has broadcasting (it's slower than Z = z(X, Y), less memory)

Z4 = z(x, y[:,None])

# note that x is still a _row_ of numbers, indexed by _columns_,

# while y[:,None] is now a _column_ of numbers, indexed by _rows_,

# so that Z4[row,column] <-- z(x[column], y[row])

# a bit of testing

# in previous answers, Z2 (i.e., explicit loops)

# is the preferred method --- here we show that the other four

# possible methods give you exactly the same result

print np.all(Z2==Z0)

print np.all(Z2==Z1)

print np.all(Z2==Z3)

print np.all(Z2==Z4)

boffi@debian:~/Documents/tmp$ python2 grid.py

True

True

True

True

boffi@debian:~/Documents/tmp$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值