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

yipeiwu_com7年前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程序设计有所帮助。

相关文章

解决pytorch GPU 计算过程中出现内存耗尽的问题

Pytorch GPU运算过程中会出现:“cuda runtime error(2): out of memory”这样的错误。通常,这种错误是由于在循环中使用全局变量当做累加器,且累加...

python 打印直角三角形,等边三角形,菱形,正方形的代码

三角形 等腰直角三角形1 2.7 #coding:utf-8 rows = int(raw_input('输入列数: ')) i = j = k = 1 #声明变量,i用于控制外层循...

pandas中去除指定字符的实例

pandas中去除指定字符的实例

例表: 假如想要去掉表中的‘#',‘;'而且以‘#'和‘;'为分割线切割数据: #将dfxA_2的每一个分隔符之间的数据提出来 col1=dfxA_2['travel_seq']...

老生常谈Python startswith()函数与endswith函数

函数:startswith() 作用:判断字符串是否以指定字符或子字符串开头 一、函数说明 语法:string.startswith(str, beg=0,end=len(string)...

Python list列表中删除多个重复元素操作示例

本文实例讲述了Python list列表中删除多个重复元素操作。分享给大家供大家参考,具体如下: 我们以下面这个list为例,删除其中所有值为6的元素: l=[9,6,5,6,6,7...