I want to calculate the values of x_new and my answer should be 0.01333,-0.02667,0.01333
x=0.02,-0.02,0.02
x_C = (x[0] x[1] x[2])/3
x_new = x-x_C
print(x_new)
CodePudding user response:
x
will become a tuple and x_C
will be float. Python doesn't support to subtract out a tuple from a float. But you can use numpy to do that.
import numpy as np
x = np.array([0.02, -0.02, 0.02])
x_C = x.mean()
x_new = x - x_C
print(x_new)
# [ 0.01333333 -0.02666667 0.01333333]
If you are not permitted to use any modules do a list comprehension.
x = 0.02, -0.02, 0.02
x_C = sum(x) / 3
x_new = [i - x_C for i in x]
print(x_new)
# [0.013333333333333332, -0.02666666666666667, 0.013333333333333332]
CodePudding user response:
You can use list comprehension, then no package imports are necessary:
x: list = [0.02,-0.02,0.02]
x_C: float = sum(x) / len(x) # (x[0] x[1] x[2])/3
print(x_C)
# 0.006666666666666667
x_new: list = [i - x_C for i in x]
print(x_new)
# [0.013333333333333332, -0.02666666666666667, 0.013333333333333332]
Just as a hint: it is always helpful to be clear about the data types used
CodePudding user response:
x is tuple, so change
x_new = x-x_C
to x_new = [i - x_C for i in x]