加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – n球面坐标系到笛卡尔坐标系

发布时间:2020-12-16 23:31:25 所属栏目:Python 来源:网络整理
导读:有没有有效的方法在笛卡尔坐标系和 n-spherical one之间进行切换?转型如下: 以下是我的代码,但我想摆脱循环: import numpy as npimport scipy.sparse def coord_transform_n(r,alpha): """alpha: the n-2 values between [0,pi) and last one between [0
有没有有效的方法在笛卡尔坐标系和 n-spherical one之间进行切换?转型如下:

以下是我的代码,但我想摆脱循环:

import numpy as np
import scipy.sparse

    def coord_transform_n(r,alpha):
        """alpha: the n-2 values between [0,pi) and last one between [0,2pi)
        """
        x=[]
        for i in range(alpha.shape[0]):
            x.append(r*np.prod(np.sin(alpha[0:i]))*np.cos(alpha[i]))
        return np.asarray(x)
    print coord_transform_n(1,np.asarray(np.asarray([1,2])))

解决方法

您可以通过记忆中间产品来加速您的原始代码,即
def ct_dynamic(r,alpha):
    """alpha: the n-2 values between [0,2pi)
    """
    x = np.zeros(len(alpha) + 1)
    s = 1
    for e,a in enumerate(alpha):
        x[e] = s*np.cos(a)
        s *= np.sin(a)
    x[len(alpha)] = s
    return x*r

但仍然在速度上失去基于numpy的方法

def ct(r,arr):
    a = np.concatenate((np.array([2*np.pi]),arr))
    si = np.sin(a)
    si[0] = 1
    si = np.cumprod(si)
    co = np.cos(a)
    co = np.roll(co,-1)
    return si*co*r

>>> n = 10
>>> c = np.random.random_sample(n)*np.pi
>>> all(ct(1,c) == ct_dynamic(1,c))
True

>>> timeit.timeit('from __main__ import coord_transform_n as f,c; f(2.4,c)',number=10000)
2.213547945022583

>>> timeit.timeit('from __main__ import ct_dynamic as f,number=10000)
0.9227950572967529

>>> timeit.timeit('from __main__ import ct as f,number=10000)
0.5197498798370361

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读