Skip to content

Instantly share code, notes, and snippets.

@nschloe
Last active February 16, 2021 12:01
Show Gist options
  • Save nschloe/a901d95bff068e93943d41ba6e4b3a3f to your computer and use it in GitHub Desktop.
Save nschloe/a901d95bff068e93943d41ba6e4b3a3f to your computer and use it in GitHub Desktop.
stackoverflow hyperplane distance
import numpy as np
import scipy.optimize
np.random.seed(0)
V_orig = np.random.rand(50, 3)
def func(x):
Vx = V_orig @ x
return np.dot(Vx, Vx)
def con(t):
return np.sum(t) - 1
x0 = np.zeros(3)
out = scipy.optimize.minimize(func, x0, constraints={"type": "eq", "fun": con})
print("optimization result:")
print(out)
print()
v0 = V_orig[:, 0]
V = np.column_stack(
[
V_orig[:, 1] - v0,
V_orig[:, 2] - v0,
]
)
u = V.T @ V
v = np.array([v0 @ V[:, 0], v0 @ V[:, 1]])
r2 = np.dot(v0, v0) + v.T @ np.linalg.inv(u) @ v
print("user result:")
print(r2)
print()
e = np.ones(3)
VTVe = np.linalg.solve(V_orig.T @ V_orig, e)
# x = VTVe / np.dot(e, VTVe)
print("nschloe result:")
print(1 / (e @ VTVe))
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment