【问题标题】:How can I obtain the coordinates for a sphere, using python?如何使用 python 获取球体的坐标?
【发布时间】:2015-04-01 19:10:12
【问题描述】:

上面的代码当前生成的是一个立方体,而不是一个球体。我该如何纠正?

x = list(range(-5,5))
y = list(range(-5,5))
z = list(range(-5,5))
r = [1,2,3,4,5,6,7,10]
xcoords = []
ycoords = []
zcoords = []
"""functions used"""
def square(number):
return number**2
"""determines which values satisfies the equation for a sphere"""
for itemx in x:
    for itemy in y:
        for itemz in z:
            for itemr in r:
                if abs(itemx) == abs(itemy) and abs(itemy) == abs(itemz) and square(itemx) + square(itemy) +square(itemz) == itemr:
                xcoords.append(itemx)
                ycoords.append(itemy)
                zcoords.append(itemz)
"""determines the number of atoms in the system"""
natoms = len(xcoords)
"""writes coords onto txt file"""
out = open("sphere.xyz", "a")
print (natoms)
out.write("%s \n \n" %(natoms))
out.close()
for item in zip(xcoords, ycoords,zcoords):
   out = open("sphere.xyz", "a")
   print (item)
   out.write( "Ar"  " " " " "%2.5s %2.5s %2.5s \n" %(item))
   out.close()

我考虑过使用球坐标来定义球体的参数,但我不知道如何使用 python 进行设置。

【问题讨论】:

  • 你能给我看一个'球点'的例子吗?其中所有坐标 (x, y, z) 和 r 都是你定义的范围内的整数?
  • 这让我想起了我对Drawing Sphere in OpenGL without using gluSphere()? 的一个旧答案。也许对你有用。
  • 我认为最大的问题是您明显假设您会在特定网格上找到坐标的球体上的点。给定网格上的质心,半径是网格间距的倍数,绝大多数球体将只有 8 个这样的点——半径上的每个方向都有一个点,与通过质心的每个轴对齐——网格对齐的边界立方体的面...

标签: python computational-geometry


【解决方案1】:

正如我在评论中提到的,我认为你是误解条件的受害者。我的方法会有所不同 - 不要迭代固定数量的坐标并尝试命中该点,而只是生成正确的点。我使用了众所周知的球面到笛卡尔公式,并为两个角度生成了固定样本。

from __future__ import division
from math import sin, cos, pi

SAMPLES = 20

def to_x(r, theta, phi):
    return r*sin(theta)*cos(phi)

def to_y(r, theta, phi):
    return r*sin(theta)*sin(phi)

def to_z(r, theta, phi):
    return r*cos(theta)

samples_r = [r for r in xrange(1, 10)]
samples_theta = [theta * pi / SAMPLES for theta in xrange(SAMPLES)]
samples_phi = [phi * 2*pi / SAMPLES for phi in xrange(SAMPLES)]

coords = []

for r in samples_r:
    for theta in samples_theta:
        for phi in samples_phi:
            coords.append((to_x(r, theta, phi), 
                           to_y(r, theta, phi),
                           to_z(r, theta, phi)))

for coord in coords:
   out = open("sphere.xyz", "a")
   print (coord)
   out.write( "Ar"  " " " " "%2.5s %2.5s %2.5s \n" %(coord))
   out.close()

为了提高内存性能,您可以考虑使用generatorsitertools 模块(尤其是itertools.product 似乎是为类似问题而设计的)。

【讨论】:

    猜你喜欢
    • 2014-09-02
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多