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

相关文章

pandas带有重复索引操作方法

有的时候,可能会遇到表格中出现重复的索引,在操作重复索引的时候可能要注意一些问题。 一、判断索引是否重复 a、Series索引重复判断 s = Series([1,2,3,4,5],...

python 函数的缺省参数使用注意事项分析

本文实例讲述了python 函数的缺省参数使用注意事项。分享给大家供大家参考,具体如下: python的函数支持4种形式的参数:分别是必选参数、 缺省参数、 可变长参数、关键字参数;而且...

python提取xml里面的链接源码详解

因群里朋友需要提取xml地图里面的链接,就写了这个程序。 代码: #coding=utf-8 import urllib import urllib.request import r...

Python制作简易注册登录系统

Python制作简易注册登录系统

这次我主要讲解如何用Python基于Flask的登录和注册,验证方式采用Basic Auth 主要用以下库 import os #Flask的基础库 from flask imp...

python代码 if not x: 和 if x is not None: 和 if not x is None:使用介绍

代码中经常会有变量是否为None的判断,有三种主要的写法: 第一种是`if x is None`; 第二种是 `if not x:`; 第三种是`if not x is None`(这句...