I have a for loop with a range of 2000 in this for loop I have to create an array called Array
out of two other arrays, let's call them ArrayOfPositionSatellite
with a size of (3,38) and the other array called ArrayOfPositionMassPoint
with a size of (38, 3, 4412). The size of Array
is (38,3,4412) and the size of PositonOfSatellite and PointsOfMassPoint is (3, ). My attempt to overwrite the ArrayOfMassPoint with to for-loops :
ArrayOfPositionSatellite= ArrayOfPositionSatellite.T
Array = ArrayOfPositionMassPoint
for i in range(38):
for k in range(4412):
PositionOfSatellite = ArrayOfPositionSatellite[:,i]
PositionOfMassPoint= ArrayOfPositionMassPoint[i,:,k]
ElementOfA = -Gravitationalconstant* (PositionOfSatellite - PositionOfMassPoint)/(np.linalg.norm( PositionOfSatellite - PositionOfMassPoint)**3)
Array[i,:,k] = ElementOfArray
Problem
My problem is that it takes around 3 hours to run the code and this is too long. Is there some way to make it more time-efficient?
If something is unclear please leave a comment and I will add more details.
You can vectorize your calculations. Like:
import numpy as np
ArrayOfPositionSatellite = np.random.randn(3, 38)
ArrayOfPositionMassPoint = np.random.randn(38, 3, 4412)
Gravitationalconstant = 6.67430e-11
# This is the difference vector
v = ArrayOfPositionMassPoint - ArrayOfPositionSatellite.T[:,:,None]
# This is norm of the difference vector
norm = np.linalg.norm(v, axis=1) ** 3
# This is normalized vector
norm_v = v / norm[:, None, :]
# This is the result
array = norm_v * -Gravitationalconstant
array.shape
>>> (38, 3, 4412)
This takes around ~40ms on my machine, instead of 3 hours.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다