internal static void Simplify(List <Term <T> > terms) { IField <T> field = (new TField()).Instance; Dictionary <int, T> termsDic = new Dictionary <int, T>(); foreach (var t in terms) { if (!termsDic.ContainsKey(t.Deg)) { termsDic.Add(t.Deg, field.Zero); } termsDic[t.Deg] = field.Add(termsDic[t.Deg], t.Coeff); } terms.Clear(); foreach (var pair in termsDic) { if (!field.IsZero(pair.Value)) { terms.Add(new Term <T>(pair.Key, pair.Value)); } } }
internal static void Add(List <Term <T> > terms, Term <T> t) { IField <T> field = (new TField()).Instance; int index; index = terms.FindIndex((t_) => t_.Deg == t.Deg); if (index != -1) { T newCoeff = field.Add(terms[index].Coeff, t.Coeff); if (!field.IsZero(newCoeff)) { terms[index] = new Term <T>(t.Deg, newCoeff); } else { terms.RemoveAt(index); } } else if (!field.IsZero(t.Coeff)) { terms.Add(t); } }
public async Task <IActionResult> _ActionField(Field field) { bool status = false; string message = ""; Guid libraryGuid = Guid.Empty; string queryGuid = Common.GetGuidFromURL(Request.Path.ToString()); if (!string.IsNullOrEmpty(queryGuid)) { libraryGuid = Guid.Parse(queryGuid); } if (!await DublicateFieldName(field, libraryGuid)) { try { if (ModelState.IsValid) { if (field.ID == 0) // Add new field { field.LibraryGuid = libraryGuid; field.GUID = Guid.NewGuid(); field.Visible = (field.IsVisible) ? 1 : 0; field.Editable = (field.IsEditable) ? 1 : 0; field.Required = (field.IsRequired) ? 1 : 0; field.Deleted = 0; await _iField.Add(field); status = true; message = field.Title + " has been added to Library."; } else // update field { field.LibraryGuid = libraryGuid; field.Visible = (field.IsVisible) ? 1 : 0; field.Editable = (field.IsEditable) ? 1 : 0; field.Required = (field.IsRequired) ? 1 : 0; field.Deleted = 0; await _iField.Update(field); status = true; message = field.Title + " has been updated."; } status = true; } } catch (Exception ex) { status = false; message = ex.Message; } } else { status = false; message = field.Name + " already exists in this Library"; } return(new JsonResult(new { success = status, message = message })); }
/// <summary> /// Divide um número complexo corrente por outro. /// </summary> /// <param name="right">O número a ser dividido.</param> /// <param name="field">O corpo responsável pelas operações.</param> /// <returns>O resultado da divisão.</returns> /// <exception cref="ArgumentNullException">Se algum dos argumentos for nulo.</exception> /// <exception cref="DivideByZeroException">Se ocorrer uma divisão por zero.</exception> public ComplexNumber <ObjectType> Divide(ComplexNumber <ObjectType> right, IField <ObjectType> field) { if (field == null) { throw new ArgumentNullException("field"); } else if (right == null) { throw new ArgumentNullException("right"); } else if (right.IsZero(field)) { throw new DivideByZeroException("Can't divide by the zero complex number."); } else { var quadReal = field.Multiply(right.realPart, right.realPart); var quadImaginary = field.Multiply(right.imaginaryPart, right.imaginaryPart); var denom = field.Add(quadReal, quadImaginary); var resReal = field.Multiply(this.realPart, right.realPart); resReal = field.Add( resReal, field.Multiply(this.imaginaryPart, right.imaginaryPart)); resReal = field.Multiply( resReal, field.MultiplicativeInverse(denom)); var resImg = field.Multiply(this.realPart, right.imaginaryPart); resImg = field.AdditiveInverse(resImg); resImg = field.Add( resImg, field.Multiply(this.imaginaryPart, right.realPart)); resImg = field.Multiply( resImg, field.MultiplicativeInverse(denom)); var result = new ComplexNumber <ObjectType>(); result.realPart = resReal; result.imaginaryPart = resImg; return(result); } }
public T Evaluate(T x) { T y = _field.Zero; foreach (Term <T> t in _terms) { y = _field.Add(y, _field.Multiply(t.Coeff, _field.Pow(x, t.Deg))); } return(y); }
public void Initialize(IField field, char[,] gridZero) { for (int row = 0; row < field.TotalRows; row++) { for (int col = 0; col < field.TotalCols; col++) { if (gridZero[row, col] == '1') { Position position = new Position(row, col); Cell cell = new Cell(CellColor.Green, position); field.Add(cell); } else { Position position = new Position(row, col); Cell cell = new Cell(CellColor.Red, position); field.Add(cell); } } } }
/// <summary> /// Vefica se o produto da matriz pelo vector actual resulta no esperado. /// </summary> /// <typeparam name="CoeffType"> /// O tipo de objectos que constituem as entradas das estruturas. /// </typeparam> /// <param name="expected">O vector esperado.</param> /// <param name="matrix">a matriz.</param> /// <param name="field"> /// O objecto responsável pelas operações sobre os coeficientes. /// </param> /// <param name="actual">O vector actual.</param> private void AssertVector <CoeffType>( IMathVector <CoeffType> expected, IMathMatrix <CoeffType> matrix, IMathVector <CoeffType> actual, IField <CoeffType> field) { var lines = matrix.GetLength(0); var columns = matrix.GetLength(1); for (var i = 0; i < lines; ++i) { var sum = field.AdditiveUnity; for (var j = 0; j < columns; ++j) { var value = field.Multiply( matrix[i, j], actual[j]); sum = field.Add(sum, value); } Assert.AreEqual(expected[i], sum); } }
public async Task <IActionResult> ActionLibrary(Models.Library library) { bool status = false; string message = ""; try { if (ModelState.IsValid) { if (library.ID == 0) //Add new { if (!await _iLibrary.CheckDuplicate(library)) { library.CreatedDate = DateTime.Now; var user = _iUser.FindByID(Convert.ToInt32(HttpContext.User.FindFirstValue(ClaimTypes.Sid))).Result; var libraryType = await _iLibraryType.FindByID((int)library.LibraryTypeID); string testid = HttpContext.User.FindFirst("GUID").ToString(); library.CreatedBy = user; library.CreatedDate = DateTime.Now; if (libraryType.Type.ToLower() == "dataview")// 1:Container,2:Data View. If library has type = 2 then create some default fields for the Data view library { var defaultFields = await _iDefaultField.DefaultFieldCollection(); foreach (var dfield in defaultFields) { Field field = new Field(); field.Name = dfield.Name; field.Title = dfield.Title; field.FieldType = dfield.FieldType; if (dfield.Name.ToLower() == "createddate" || (dfield.Name.ToLower() == "createdby")) { field.Editable = 0; field.Visible = 0; } else { field.Editable = 1; field.Visible = 1; } field.Library = library; field.LibraryGuid = library.GUID; await _iField.Add(field); } } await Task.FromResult(_iLibrary.Add(library)); status = true; message = "Library " + library.Title + " has been added!"; } else { status = false; message = "Library " + library.Title + " already exist!"; } } else { if (!await _iLibrary.CheckDuplicate(library)) { library.EditedBy = _iUser.FindByID(Convert.ToInt32(HttpContext.User.FindFirstValue(ClaimTypes.Sid))).Result; library.EditedDate = DateTime.Now; await _iLibrary.Edit(library); status = true; message = "Library " + library.Title + " has been updated!"; } else { status = false; message = "Library " + library.Title + " already exist!"; } } } else { message = "Model State is not valid. "; message += string.Join("; ", ModelState.Values .SelectMany(x => x.Errors) .Select(x => x.ErrorMessage)); status = false; } } catch (Exception ex) { status = false; message = ex.Message; } return(new JsonResult(new { success = status, message = message })); }
/// <summary> /// Determina a inversa da matriz correspondente à decomposição especificada. /// </summary> /// <param name="decompositionResult">A decomposição.</param> /// <param name="matrixFactory">A fábrica responsável pela criação da matriz resultante.</param> /// <param name="field">O corpo responsável pelas operações sobre os objectos.</param> /// <returns>A inversa da matriz associada à decomposição.</returns> /// <exception cref="ArgumentNullException">Se algums dos argumentos for nulo.</exception> public IMathMatrix <CoeffType> Run( TriangDiagSymmMatrixDecompResult <CoeffType> decompositionResult, ISquareMatrixFactory <CoeffType> matrixFactory, IField <CoeffType> field) { if (field == null) { throw new ArgumentNullException("field"); } else if (matrixFactory == null) { throw new ArgumentNullException("matrixFactory"); } else if (decompositionResult == null) { throw new ArgumentNullException("decompositionResult"); } else { var dimension = decompositionResult.UpperTriangularMatrix.GetLength(0); for (var i = 0; i < dimension; ++i) { var d = decompositionResult.DiagonalMatrix[i, i]; if (field.IsAdditiveUnity(d)) { throw new MathematicsException("The provided decomposition has no inverse."); } } var result = matrixFactory.CreateMatrix(dimension); for (int j = dimension - 1; j >= 0; --j) { // Elemento na diagonal. var i = j; var diagonalValue = field.MultiplicativeInverse( decompositionResult.DiagonalMatrix[i, j]); var k = i + 1; for (; k < dimension; ++k) { var product = field.Multiply( decompositionResult.UpperTriangularMatrix[i, k], result[i, k]); diagonalValue = field.Add( diagonalValue, field.AdditiveInverse(product)); } result[i, j] = diagonalValue; --i; while (i >= 0) { k = i + 1; var upperValue = field.Multiply( decompositionResult.UpperTriangularMatrix[i, k], result[k, j]); upperValue = field.AdditiveInverse(upperValue); ++k; for (; k <= j; ++k) { var product = field.Multiply( decompositionResult.UpperTriangularMatrix[i, k], result[k, j]); upperValue = field.Add( upperValue, field.AdditiveInverse(product)); } // Como a matriz é simétrica, inverte a orientação. for (; k < dimension; ++k) { var product = field.Multiply( decompositionResult.UpperTriangularMatrix[i, k], result[j, k]); upperValue = field.Add( upperValue, field.AdditiveInverse(product)); } result[i, j] = upperValue; --i; } } this.SetLowerTerms(result); return(result); } }
public static Polynomial <T, TField> Divide(Polynomial <T, TField> p1, Polynomial <T, TField> p2, out Polynomial <T, TField> rem) { IField <T> field = p1.Field; T leadingCoeff; T[] dividList; T[] divisList; T[] quotList; T[] workList; if (p2.Degree > p1.Degree) { rem = p1; return(Polynomial <T, TField> .Zero); } if (p2.Degree == 0) { rem = new Polynomial <T, TField>(); return(Divide(p1, p2[0].Coeff)); } dividList = p1.ToCoefficientList(); divisList = p2.ToCoefficientListForDivisor(out leadingCoeff); quotList = new T[p1.Degree - p2.Degree + 1]; workList = new T[divisList.Length]; if (!field.IsOne(leadingCoeff)) { // Fix the dividend. for (int i = 0; i < dividList.Length; i++) { dividList[i] = field.Divide(dividList[i], leadingCoeff); } } // Initialize the work list. Array.Copy(dividList, workList, workList.Length); for (int i = 0; i < quotList.Length; i++) { // Save the quotient cofficient. quotList[i] = workList[0]; // Shift left, take in from dividend. Array.Copy(workList, 1, workList, 0, workList.Length - 1); workList[workList.Length - 1] = dividList[i + workList.Length]; // Copy the divisor and multiply with the last quotient // coefficient. Add this to the work list. Note that this // is all done in one step. for (int j = 0; j < workList.Length; j++) { workList[j] = field.Add(workList[j], field.Multiply(divisList[j], quotList[i])); } } if (!field.IsOne(leadingCoeff)) { // Fix the remainder. for (int i = 0; i < workList.Length; i++) { workList[i] = field.Multiply(workList[i], leadingCoeff); } } rem = FromCoefficientList(workList); return(FromCoefficientList(quotList)); }