【问题标题】:python: converting numpy array to fixed float numberspython:将numpy数组转换为固定浮点数
【发布时间】:2020-12-04 16:31:53
【问题描述】:

我正在处理一个 Python 函数,它计算代表 XYZ 坐标的嵌套数组的所有元素的几何中心

  def lig_center(nested_array_list):
        a = numpy.array(nested_array_list)
        mean = numpy.mean(a, axis=0)
        return mean[0], mean[1], mean[2]  # x, y, z
    
# input list 

xyz= [[121.133, 146.696, 139.126], [121.207, 145.489, 138.437], [122.058, 145.337, 137.335], [121.972, 143.689, 136.593], [123.209, 143.616, 135.31], [124.536, 143.881, 135.697], [124.87, 145.234, 135.928], [126.179, 145.569, 136.301], [127.156, 144.591, 136.455], [126.838, 143.258, 136.229], [123.824, 146.34, 135.736], [125.543, 142.913, 135.853], [123.008, 142.449, 134.454], [120.662, 143.598, 135.938], [122.362, 142.722, 137.625], [122.857, 146.427, 136.913], [122.764, 147.633, 137.625], [121.914, 147.77, 138.718], [123.101, 146.373, 134.374], [122.534, 147.208, 134.333], [122.482, 145.576, 134.33], [124.016, 146.346, 133.138], [125.066, 147.46, 133.272], [124.449, 148.847, 133.177], [123.972, 149.313, 131.947], [123.409, 150.582, 131.856], [123.322, 151.385, 132.993], [123.796, 150.925, 134.221], [124.36, 149.655, 134.314], [122.769, 152.634, 132.905], [123.339, 153.323, 133.255]]
# calculate geonetrical center of each element of xyz
col=lig_center(xyz)
# result"(123.51000000000001, 146.66999999999999, 135.30000000000001)

如何获得以下格式的 col 结果:

# just three float numbers with fixed number of digits after .
123.510 146.669 135.300

【问题讨论】:

  • 1.阅读“每个程序员都应该了解的浮点数知识”。 2.通过在输出时格式化数字来处理这个问题,指定3位数字,你会得到你想要的效果。
  • 我可以直接从函数 #print("[%.3f, %.3f, %.3f]" % tuple(mean)) 打印它但我需要将它保存在返回的变量中脚本

标签: python numpy floating-point


【解决方案1】:

使用numpy.around 将数组中的所有值四舍五入到指定的小数位数:

import numpy as np
...
col = np.around(col, 3)

【讨论】:

  • 我已经试过了。它有时会在某些值中给出更少的数字:例如数组([ 123.51, 146.67, 135.3 ]),而我需要在所有三个数字中保持相同的数字
  • 位数较少意味着浮点数是完全四舍五入的,即在它停止的点之后只有 0。如果您确实需要像这样的一致格式,则必须转换为字符串,例如list(map(lambda x: format(x, ".3f"), col))
猜你喜欢
  • 2021-12-28
  • 1970-01-01
  • 2020-05-14
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
  • 1970-01-01
相关资源
最近更新 更多