I am dealing with a Python function that compute geometrical center for all elements of nestled array representing XYZ coordinates
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)
how I could obtain result of col in the following format:
# just three float numbers with fixed number of digits after .
123.510 146.669 135.300
asked Dec 4, 2020 at 16:31
user14748664
-
11. Read "what every programmer should know about floating point numbers". 2. Handle this by formatting the numbers upon output, specifying 3 digits and you will get the effect you want.Tarik– Tarik2020年12月04日 16:36:27 +00:00Commented Dec 4, 2020 at 16:36
-
I could print it directly from function #print("[%.3f, %.3f, %.3f]" % tuple(mean)) BUT I need to save this in a variable returned to the scriptuser14748664– user147486642020年12月04日 16:40:08 +00:00Commented Dec 4, 2020 at 16:40
1 Answer 1
Use numpy.around to round all values in an array to a specified number of decimals:
import numpy as np
...
col = np.around(col, 3)
Sign up to request clarification or add additional context in comments.
2 Comments
dschurman
The smaller number of digits means that the float was fully rounded, i.e. only 0's after the point it stops. If you truly need consistent formatting like this, you'll have to convert to strings, for example
list(map(lambda x: format(x, ".3f"), col))lang-py