def find_idx_with_nonzero(self, coeficient_idx, start_idx=0): """Find the first equation index where coeficient "coeficient_idx" is not zero. Args: coeficient_idx(int): The index of the coefficient to check. start_idx(int): Start the search in this row of the system. Returns: bool: Returns False if there is not an equation in this system with coefficient "coeficient_idx" different than zero. int: Returns the index of the equation with the first non-zero coefficient in variable "coeficient_idx". Default value is zero. Raises: IndexError: If start_idx is out of the bounds of self.planes array. """ for i in range(start_idx, len(self.planes)): row_var_value = self.planes[i].normal_vector[coeficient_idx] row_var_value = MyDecimal(row_var_value) if(not row_var_value.is_near_zero()): return i return False
def compute_triangular_form(self): """This function will return a different copy of this system in triangular form. Returns: LinearSystem: A new system equals to this one in triangular form. """ system = deepcopy(self) n = system.dimension j= 0 for i,_ in enumerate(system.planes): while j < n: c = MyDecimal(system.planes[i].normal_vector[j]) if c.is_near_zero(): row_with_nonzero = system.find_idx_with_nonzero(j, i) if row_with_nonzero: system.swap_rows(i, row_with_nonzero) else: j += 1 continue; system.clear_var(i,j) j += 1 break; return system
def var_count(self): """Returns a count of the number of variables present in the equation. Returns: int: Count of variables in this plane's equation. """ var_count = 0; for _, coefficient in enumerate(self.normal_vector): var_coefficient = MyDecimal(coefficient) if(not var_coefficient.is_near_zero()): var_count += 1 return var_count
def solve(self): """Returns the solution of this system of equation. Returns: vector.Vector: If there is an unique solution, will return a vector representing the x,y,z points of the solution. bool: False if there is no solution and True if there are many solutions. """ rref = self.compute_rref() unique_solution = ['0','0','0'] first_nonzeros = rref.indices_of_first_nonzero_terms_in_each_row() response = None one_variable_alone = False single_solution = True for i,plane in enumerate(rref.planes): pivot_var_idx = first_nonzeros[i] constant_term = MyDecimal(plane.constant_term) if(pivot_var_idx < 0 and not constant_term.is_near_zero() ): return False number_of_vars = rref[i].var_count() if(number_of_vars == 1): one_variable_alone = True unique_solution[pivot_var_idx] = plane.constant_term/plane.normal_vector[pivot_var_idx] elif(number_of_vars > 1): single_solution = False if(one_variable_alone and not single_solution): response = False elif(not one_variable_alone and not single_solution): response = True else: response = unique_solution return response