Python实现将n个点均匀地分布在球面上的方法

yipeiwu_com6年前Python基础

本文实例讲述了Python实现将n个点均匀地分布在球面上的方法。分享给大家供大家参考。具体分析如下:

最近工作上遇到一个需求,将10000左右个点均匀地分布在一个球面上。所谓的均匀,即相邻的两个点之间的距离尽量一致。
我的算法是用基于正多面体剖分球面,我选的是正八面体。

1. 效果图如下:

2.sphere.py代码如下

#!/usr/bin/python
# -*- coding: utf-8 -*-
import math
class Spherical(object):
  '''球坐标系'''
  def __init__(self, radial = 1.0, polar = 0.0, azimuthal = 0.0):
    self.radial = radial
    self.polar = polar
    self.azimuthal = azimuthal
  def toCartesian(self):
    '''转直角坐标系'''
    r = math.sin(self.azimuthal) * self.radial
    x = math.cos(self.polar) * r
    y = math.sin(self.polar) * r
    z = math.cos(self.azimuthal) * self.radial
    return x, y, z
def splot(limit):
  s = Spherical()
  n = int(math.ceil(math.sqrt((limit - 2) / 4)))
  azimuthal = 0.5 * math.pi / n
  for a in range(-n, n + 1):
    s.polar = 0
    size = (n - abs(a)) * 4 or 1
    polar = 2 * math.pi / size
    for i in range(size):
      yield s.toCartesian()
      s.polar += polar
    s.azimuthal += azimuthal
for point in splot(input('')):
  print("%f %f %f" % point)

希望本文所述对大家的Python程序设计有所帮助。

相关文章

bpython 功能强大的Python shell

bpython 功能强大的Python shell

Python是一个非常实用、流行的解释型编程语言,其优势之一就是可以借助其交互的shell进行探索式地编程。你可以试着输入一些代码,然后马上获得解释器的反馈,而不必专门写一个脚本。但是P...

Python编写Windows Service服务程序

Python编写Windows Service服务程序

 如果你想用Python开发Windows程序,并让其开机启动等,就必须写成windows的服务程序Windows Service,用Python来做这个事情必须要借助第三方模...

Python中的is和id用法分析

本文实例讲述了Python中的is和id用法。分享给大家供大家参考。具体分析如下: (ob1 is ob2) 等价于 (id(ob1) == id(ob2)) 首先id函数可以获得对象的...

Python中sort和sorted函数代码解析

本文研究的主要是Python中sort和sorted函数的相关内容,具体如下。 一、sort函数 sort函数是序列的内部函数 函数原型: L.sort(cmp=None, key=No...

python中文件变化监控示例(watchdog)

在python中文件监控主要有两个库,一个是pyinotify ( https://github.com/seb-m/pyinotify/wiki ),一个是watchdog(http:...