'Python Array Element Assignment bug? [Fixed]
I'm trying to assign an array element to a number but it keeps resetting back to 0 once printed or used. The sum and the multiple just become 0.
I'm trying to plot a line as a result of linear regression in 3D
Is it a bug or am I doing something wrong?
Example:
x1[i] = a2D[i][0] - xmean
print(a2D[i][0], xmean, x1[i], a2D[i][0] - xmean)
# Output: 0.1 0.045 0.0 0.05500000000000001
# Expected Output: 0.1 0.045 0.05500000000000001 0.05500000000000001
How to fix it?
Python version: Python 3.9.7
OS: Windows 11
Full Code:
# importing mplot3d toolkits
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
import random
fig = plt.figure()
a1D = np.array([[0,0,0]])
a2D = np.array([[0,0,0]])
pointcount = 10
for i in range(1,pointcount):
x = i/10
y = i/10 + random.randint(-2,2)
z = 0
a2D = np.concatenate((a2D, [[x,y,z]]), axis = 0)
xmean, ymean, zmean = 0,0,0
xsum, ysum, zsum = 0,0,0
emp = [0 for i in range(100)]
x1, y1, z1 = emp,emp,emp
xsquare = emp
xymult = emp
xzmult = emp
"""
Fixed
x1, y1, z1 = [0] * 100,[0] * 100,[0] * 100
xsquare = [0] * 100
xymult = [0] * 100
xzmult = [0] * 100
"""
xysum = 0
xzsum = 0
xsquaresum = 0
for i in range(1,pointcount):
xsum += a2D[i][0]
ysum += a2D[i][1]
zsum += a2D[i][2]
xmean, ymean, zmean = xsum/100, ysum/100, zsum/100
print(xmean, ymean, zmean)
for i in range(1,pointcount):
x1[i] = a2D[i][0] - xmean
y1[i] = a2D[i][1] - ymean
z1[i] = a2D[i][2] - zmean
print(a2D[i][0], xmean, x1[i], a2D[i][0] - xmean)
xsquare[i] = x1[i] * x1[i]
xymult[i] = x1[i] * y1[i]
xzmult[i] = x1[i] * z1[i]
xsquaresum += xsquare[i]
xysum += xymult[i]
xzsum += xzmult[i]
#print(xzmult[i])
print(xysum, xsquaresum)
print(xzsum, xsquaresum)
m1 = xysum/xsquaresum
m2 = xzsum/xsquaresum
c1 = ymean - m1*xmean
c2 = zmean - m2*xmean
print(m1, c1)
print(m2, c2)
print(a2D[0])
for i in range(1,100):
t = i/10
x = t
y = m1*t + c1
z = m2*t + c2
a1D = np.concatenate((a1D, [[x,y,z]]), axis = 0)
#print(a1D)
# syntax for 3-D projection
ax = fig.add_subplot(111, projection='3d')
ax.plot3D(a1D[:,0], a1D[:,1], a1D[:,2])
ax.plot3D(a2D[:,0], a2D[:,1], a2D[:,2], color='green')
sc = ax.scatter(a2D[:,0], a2D[:,1], a2D[:,2], color='green', s=0.5)
# syntax for plotting
ax.set_title('3d Scatter Plot')
fig.show()
plt.pause(-1)
[Output in Terminal][1] [1]: https://i.stack.imgur.com/zXYX4.png
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
