Home > Enterprise >  Scaling tuples using different scales in Python
Scaling tuples using different scales in Python

Time:11-06

I am trying to scale three vectors with three different scale for each of the vectors, and then find the linear combination of the vectors to find a single point.

The vectors are three corners of a quilateral triangle, and the scales are randomly selected.

w_list = np.zeros(3)
sum = 0
for i in range(3):
    w_list[i] = np.random.random_sample()
    sum  = w_list[i]

w = w_list/sum  # scaling weights

corners = [(0, 0), (1, 0), (0.5, np.sqrt(3/4))]

x = 0, 0
for i, e in zip(w, corners):   # w contains the three scales
     x  = (i * e[0], i * e[1])

However, when I print x I get a number a vector with 7 points when it should just print one point.

(0, 0, 0.0, 0.0, 0.4682062316923167, 0.0, 0.15138058449552882, 0.26219886362572936)

CodePudding user response:

While not strictly necessary to solve your problem, it might be useful for you to get accustomed to using numpy to its full potential. It is really very powerful and can speed up all your calculations by a factor of a hundred.

import numpy as np
corners = np.array([(0, 0), (1, 0), (0.5, np.sqrt(3/4))])
weights = np.random.random(3)
weights /= np.sum(weights)  # normalization
x = np.dot(weights, corners)

CodePudding user response:

try the below (using list and tuple as x)

import numpy as np
corners = [(0, 0), (1, 0), (0.5, np.sqrt(3/4))]
w = [1,2,3]
x = [0, 0]
for i, e in zip(w, corners):   # w contains the three scales
     x[0]= x[0]   i * e[0]
     x[1]= x[1]   i * e[1]

print(x)

output

[3.5, 2.598076211353316]

CodePudding user response:

You are currently doing tuple concatenation rather than vector addition (note that the final tuple in your question has 8 rather than 7 numbers). Instead, make your x a numpy array:

import numpy as np

w_list = np.zeros(3)
sum = 0
for i in range(3):
    w_list[i] = np.random.random_sample()
    sum  = w_list[i]

w = w_list/sum  # scaling weights

corners = [(0, 0), (1, 0), (0.5, np.sqrt(3/4))]

x = np.array([0.0, 0.0]) #don't want an int array

for i, e in zip(w, corners):   # w contains the three scales
     x  = (i * e[0], i * e[1])
     
print(x) #[0.25691217 0.4105851 ]
  • Related