1
votes

I'm trying to solve 3 equations with 3 variables. So far I have been successful in doing this using GEKKO, however the calculation is much too slow in GEKKO for my application. Therefor I am trying to get the equations to work in numpy.

My problem is with breaking the equation down into the array. I will copy my code below to help explain my problem better. The first will be the GECKO code and the second, the numpy attempt.

The equation is trying to solve for Xn, Yn, Zn.

    Xn = m.Var()
    Yn = m.Var()
    Zn = m.Var()

    m.Equation((X3 - Xn)**2 + (Y3 - Yn)**2 + (Z3 - Zn)**2 == chord_2**2)
    m.Equation((Xc - Xn)**2 + (Yc - Yn)**2 + (Zc - Zn)**2 == R**2)
    m.Equation((X1 - Xn)**2 + (Y1 - Yn)**2 + (Z1 - Zn)**2 == chord_3**2)

    m.solve(disp=False)
    print(Xn.value)
    print(Yn.value)
    print(Zn.value)
    print()

returns: [2.1594220718]
         [1.9266668526]
         [4.7244269684]

Please forgive the numpy attempt as I was just playing with it at this stage.

    A = np.array([[(X3-1)**2, (Y3-1)**2, (Z3-1)**2],
                  [(Xc-1)**2, (Yc-1)**2, (Zc-1)**2],
                  [(X1-1)**2, (Y1-1)**2, (Z -1)**2]])

    B = np.array([chord_2**2, R**2, chord_3**2])
    ans = np.linalg.solve(A,B)
    print(ans)

returns: [0.6453685  2.11823391 0.02638476]

As you can see the answer obviously isn't correct.

Any help would be greatly appreciated. Thanks!

Thanks for to replies, I will add the variable Values below.

X1 = 2.0
Y1 = 1.5
Z1 = 6.0

X3 = 11.75
Y3 = 6.25
Z3 = 0.0

Xc = 9.44449509
Yc = 3.50380186
Zc = 6.88156432

chord_2 = 11.532155223590282
R = 7.759696168825623
chord_3 = 1.3544541258839005

for example if the three equations wer:

x + 2y + z = 2
2x - 3y + z = -1
5x - y - 2z = -3

I would fill the array in as follows:

A = np.array([[1, 2, 1],
              [2, -3, 1],
              [5, -1, -2]])
B = np.array([2, -1, -3])
ans = np.linalg.solve(A,B)
print(ans)

returns: [1. 2. 3.]

I want to do the same as this but with my 3 equations. Thanks for your help!

2
Please share your constant values and equations in mathematical form so we can help better. I am not familiar with GECKO and do not know how to interpret your code. - Ehsan

2 Answers

1
votes

Like this:

import numpy as np

arr = np.arange(1, 9 + 1).reshape(3, 3)

Example array:

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

The equation:

np.power(np.subtract(5, arr), 2)
array([[16,  9,  4],
       [ 1,  0,  1],
       [ 4,  9, 16]])
0
votes

I found a solution using scipy. code is as follows:

from scipy.optimize import fsolve

    def equations(p):

        Xn, Yn, Zn = p
        return ((X3 - Xn)**2 + (Y3 - Yn)**2 + (Z3 - Zn)**2 - chord_2**2,
                (Xc - Xn)**2 + (Yc - Yn)**2 + (Zc - Zn)**2 - R**2,
                (X1 - Xn)**2 + (Y1 - Yn)**2 + (Z1 - Zn)**2 - chord_3**2)


    Xn, Yn, Zn = fsolve(equations, (1,1,1))
    print(Xn)
    print(Yn)
    print(Zn)

This gives the correct answers and and runs much faster.