private Complex postFixedOperatorEvaluator(List<Complex> values, string tokenString) { //TODO: Solve these problems in cases that cannot be evaluated numerically. //Possibly extend the Value type for non-numerical evaluation. Factors factors; Complex returnVal = values.Last(); List<int> listOfFactors = new List<int>(); if (tokenString == "!") { if (values.Count() > 1) throw new Exception("suffix notation can only have one child"); for (int i = 2; i < returnVal.Real + 1; i++) { listOfFactors.Add(i); } factors = new Factors(listOfFactors); return returnVal.Factorial(); } for (int i = values.Count() - 2; i >= 0; i--) switch (tokenString) { case "+": returnVal += values[i]; break; case "-": returnVal -= values[i]; break; case "*": returnVal *= values[i]; //TODO: Combine factors into a new factors list so the result doesn't need to be factored break; case "/": returnVal /= values[i]; break; case "%": returnVal = returnVal.Modulus(values[i]); break; case "^": if (values.Count() > 2) throw new Exception("Can't have more than two parameters for the power method."); returnVal = MathNet.Numerics.ComplexExtensions.Power(returnVal, values[i]); break; case "Sum": returnVal += values[i]; break; default: throw new Exception("unknown operator"); } if (returnVal == int.MinValue) throw new Exception("No evaluation happened"); return returnVal; }
/// <summary> /// Solves a system of linear equations, <c>AX = B</c>, with A LU factorized. /// </summary> /// <param name="input">The right hand side <see cref="Matrix{T}"/>, <c>B</c>.</param> /// <param name="result">The left hand side <see cref="Matrix{T}"/>, <c>X</c>.</param> public override void Solve(Matrix <double> input, Matrix <double> result) { // Check for proper arguments. if (input == null) { throw new ArgumentNullException(nameof(input)); } if (result == null) { throw new ArgumentNullException(nameof(result)); } // Check for proper dimensions. if (result.RowCount != input.RowCount) { throw new ArgumentException(Resources.ArgumentMatrixSameRowDimension); } if (result.ColumnCount != input.ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSameColumnDimension); } if (input.RowCount != Factors.RowCount) { throw Matrix.DimensionsDontMatch <ArgumentException>(input, Factors); } // Copy the contents of input to result. input.CopyTo(result); for (var i = 0; i < Pivots.Length; i++) { if (Pivots[i] == i) { continue; } var p = Pivots[i]; for (var j = 0; j < result.ColumnCount; j++) { var temp = result.At(p, j); result.At(p, j, result.At(i, j)); result.At(i, j, temp); } } var order = Factors.RowCount; // Solve L*Y = P*B for (var k = 0; k < order; k++) { for (var i = k + 1; i < order; i++) { for (var j = 0; j < result.ColumnCount; j++) { var temp = result.At(k, j) * Factors.At(i, k); result.At(i, j, result.At(i, j) - temp); } } } // Solve U*X = Y; for (var k = order - 1; k >= 0; k--) { for (var j = 0; j < result.ColumnCount; j++) { result.At(k, j, (result.At(k, j) / Factors.At(k, k))); } for (var i = 0; i < k; i++) { for (var j = 0; j < result.ColumnCount; j++) { var temp = result.At(k, j) * Factors.At(i, k); result.At(i, j, result.At(i, j) - temp); } } } }
//Calcuation Controller Action public void CalculateAction(List<CategoryViewModel> jCategory) { foreach (var group in jCategory) { foreach (var item in group.Functions) { if (item.Function == "Input") { item.Output = InputFunctions.Output(item.Type, item.Output); OutputList.Add(new OutputList { ID = Convert.ToString(item.ID), Field = item.Name, Value = item.Output, Group = group.Name }); } else { //Logic check at Column Level string colLogic = null; bool colLogicParse = true; if(group.Logic != null) { foreach (var bit in group.Logic) { var grouplastLogic = group.Logic.Last(); string grouplastLogicOperator = grouplastLogic.Operator; Logic Logic = new Logic(); colLogic = Logic.Output(jCategory, bit, group.ID, 0); Expression ex = new Expression(colLogic); try { colLogicParse = Convert.ToBoolean(ex.Evaluate()); } catch (Exception exception) { logger.Error(exception); throw new HttpException(exception.ToString()); } if (grouplastLogicOperator == "AND" && colLogicParse == false) { break; } else if (grouplastLogicOperator == "OR" && colLogicParse == true) { colLogicParse = true; break; } } } if (item.Parameter.Count > 0) { string logic = null; bool logicparse = true; string MathString = null; bool PowOpen = false; //Logic check at column level if (colLogicParse == true) { foreach (var bit in item.Logic) { var lastLogic = item.Logic.Last(); string lastLogicOperator = lastLogic.Operator; Logic Logic = new Logic(); logic = Logic.Output(jCategory, bit, group.ID, item.ID); Expression ex = new Expression(logic); try { logicparse = Convert.ToBoolean(ex.Evaluate()); } catch (Exception exception) { logger.Error(exception); throw new HttpException(exception.ToString()); } if (lastLogicOperator == "AND" && logicparse == false) { break; } else if (lastLogicOperator == "OR" && logicparse == true) { logicparse = true; break; } } } else { logicparse = false; } //Run code if logic if met at column and row level if (logicparse == true) { int paramCount = 1; foreach (var param in item.Parameter) { string jparameters = Newtonsoft.Json.JsonConvert.SerializeObject(param); logger.Debug("Column Name(" + group.ID + ") - " + group.Name + " || Row Name(" + item.ID +") - " + item.Name); if (item.Function == "Maths") { Maths Maths = new Maths(); Maths parameters = (Maths)javaScriptSerializer.Deserialize(jparameters, typeof(Maths)); MathString = Maths.Output(jparameters,jCategory,group.ID,item.ID,MathString,PowOpen); PowOpen = Maths.PowOpen(jparameters, PowOpen); if (paramCount == item.Parameter.Count) { Expression e = new Expression(MathString); var Calculation = e.Evaluate(); bool DeciParse; decimal CalculationDeci; string Rounding; DeciParse = decimal.TryParse(Convert.ToString(Calculation), out CalculationDeci); Rounding = Convert.ToString(parameters.Rounding); if (Rounding == null || Rounding == "") { Rounding = "2"; } if (DeciParse == true) { decimal Output = CalculationDeci; MathematicalFunctions MathematicalFunctions = new MathematicalFunctions(); try { Output = MathematicalFunctions.Rounding(Convert.ToString(parameters.RoundingType), Rounding, Output); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } item.Output = Convert.ToString(Output); } else { item.Output = "0"; } } paramCount = paramCount + 1; } else if (item.Function == "ErrorsWarnings") { ErrorsWarnings Errors = new ErrorsWarnings(); ErrorsWarnings parameters = (ErrorsWarnings)javaScriptSerializer.Deserialize(jparameters, typeof(ErrorsWarnings)); item.Name = parameters.Type; item.Output = parameters.String1; } else if (item.Function == "Comments") { Comments Errors = new Comments(); Comments parameters = (Comments)javaScriptSerializer.Deserialize(jparameters, typeof(Comments)); item.Output = parameters.String1; } else if (item.Function == "Period") { DateFunctions DateFunctions = new DateFunctions(); Period Periods = new Period(); try { item.Output = Periods.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } } else if (item.Function == "Factors") { Factors Factors = new Factors(); Factors parameters = (Factors)javaScriptSerializer.Deserialize(jparameters, typeof(Factors)); try { item.Output = Factors.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } item.Type = parameters.OutputType; } else if (item.Function == "DateAdjustment") { Dates Dates = new Dates(); try { item.Output = Dates.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } } else if (item.Function == "DatePart") { DatePart DateParts = new DatePart(); try { item.Output = DateParts.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } } else if (item.Function == "MathsFunctions") { MathsFunctions MathsFunctions = new MathsFunctions(); try { item.Output = MathsFunctions.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } } else if (item.Function == "ArrayFunctions") { ArrayFunctions ArrayFunctions = new ArrayFunctions(); ArrayFunctions parameters = (ArrayFunctions)javaScriptSerializer.Deserialize(jparameters, typeof(ArrayFunctions)); try { item.Output = ArrayFunctions.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } if(parameters.Function == "Count") { item.Type = "Decimal"; } else { item.Type = parameters.LookupType; } } else if (item.Function == "StringFunctions") { StringFunctions StringFunctions = new StringFunctions(); StringFunctions parameters = (StringFunctions)javaScriptSerializer.Deserialize(jparameters, typeof(StringFunctions)); try { item.Output = StringFunctions.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } if(parameters.Type == "Len") { item.Type = "Decimal"; } else { item.Type = "String"; } } } //Expected results on the builder this sets the required ones if (item.ExpectedResult == null || item.ExpectedResult == "") { item.Pass = "******"; } else if (item.ExpectedResult == item.Output) { item.Pass = "******"; } else { item.Pass = "******"; } OutputList.Add(new OutputList { ID = Convert.ToString(item.ID), Field = item.Name, Value = item.Output, Group = group.Name }); } else { //Ignores the row if logic is not met dynamic LogicReplace = Config.VariableReplace(jCategory, item.Name, group.ID, item.ID); if(Convert.ToString(LogicReplace) == Convert.ToString(item.Name)) { item.Output = null; } else { item.Output = Convert.ToString(LogicReplace); } item.Pass = "******"; OutputList.Add(new OutputList { ID = Convert.ToString(item.ID), Field = item.Name, Value = item.Output, Group = group.Name }); } } } } } }
private string DoCalculation(string[] attribute) { #region Factors if (spinner[0] == (int)Calculate.Factors) { return(Factors.ShowFactors(ExtractValue <int>(attribute[0]), ExtractValue <double>(attribute[1]))); } #endregion #region Future Value else if (spinner[0] == (int)Calculate.FutureValue) { switch (spinner[1]) { case (int)Interest.IntrestType.Simple: return(Interest.FutureValue.SimpleInterest(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <double>(attribute[2]))); case (int)Interest.IntrestType.Discursive: if (spaces == 2) { return(Interest.FutureValue.CDiscursiveInterest(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <double>(attribute[2]))); } else if (spaces == 4) { return(Interest.FutureValue.CDiscursiveInterest(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <double>(attribute[2]), ExtractValue <double>(attribute[3]), (Interest.InterestPeriods)ExtractValue <int>(attribute[4]))); } break; case (int)Interest.IntrestType.Anticipative: if (spaces == 2) { return(Interest.FutureValue.CAnticipativeInterest(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <double>(attribute[2]))); } else if (spaces == 4) { return(Interest.FutureValue.CAnticipativeInterest(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <double>(attribute[2]), ExtractValue <double>(attribute[3]), (Interest.InterestPeriods)ExtractValue <int>(attribute[4]))); } break; } } #endregion #region Present Value else if (spinner[0] == (int)Calculate.PresentValue) { switch (spinner[1]) { case (int)Interest.IntrestType.Simple: return(Interest.PresentValue.SimpleInterest(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <double>(attribute[2]))); case (int)Interest.IntrestType.Discursive: if (spaces == 2) { return(Interest.PresentValue.CDiscursiveInterest(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <double>(attribute[2]))); } else if (spaces == 4) { return(Interest.PresentValue.CDiscursiveInterest(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <double>(attribute[2]), ExtractValue <double>(attribute[3]), (Interest.InterestPeriods)ExtractValue <int>(attribute[4]))); } break; case (int)Interest.IntrestType.Anticipative: if (spaces == 2) { return(Interest.PresentValue.CAnticipativeInterest(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <double>(attribute[2]))); } else if (spaces == 4) { return(Interest.PresentValue.CAnticipativeInterest(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <double>(attribute[2]), ExtractValue <double>(attribute[3]), (Interest.InterestPeriods)ExtractValue <int>(attribute[4]))); } break; } } #endregion #region Effective Interest Rate else if (spinner[0] == (int)Calculate.EffectiveIR) { return(Interest.EffectiveIR.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <double>(attribute[1]), (Interest.InterestPeriods)ExtractValue <int>(attribute[2]))); } #endregion #region Rate of Return else if (spinner[0] == (int)Calculate.RateOfReturn) { return(RateOfReturn.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]))); } #endregion #region Risk else if (spinner[0] == (int)Calculate.Risk) { switch (spinner[1]) { case (int)Risk.CalcType.ExpectedReturns: return(Risk.ExpectedReturns.ER.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]))); case (int)Risk.CalcType.StandardDeviation: return(Risk.StandardDeviation.sD.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), (attribute[2] == "0") ? Risk.ExpectedReturns.ER.Value : ExtractValue <decimal>(attribute[2]))); // if Expected Returns is equal to 0, the app will use Risk.ExpectedReturns.ER's data case (int)Risk.CalcType.VariationCoefficient: return(Risk.VariationCoefficient.Calculate((attribute[0] == "0") ? Risk.StandardDeviation.sD.Value : ExtractValue <decimal>(attribute[0]), (attribute[1] == "0") ? Risk.ExpectedReturns.ER.Value : ExtractValue <decimal>(attribute[1]))); case (int)Risk.CalcType.PortfolioCovariation: return(Risk.PortfolioCovariation.PC.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <decimal>(attribute[2]), ExtractValue <decimal>(attribute[3]), ExtractValue <decimal>(attribute[4]))); case (int)Risk.CalcType.CorelationCoefficient: return(Risk.CorelationCoefficient.CC.Calculate((attribute[0] == "0") ? Risk.PortfolioCovariation.PC.Value : ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <decimal>(attribute[2]))); case (int)Risk.CalcType.PortfolioDeviation: return(Risk.PortfolioDeviation.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <decimal>(attribute[2]), ExtractValue <decimal>(attribute[3]), (attribute[4] == "0") ? Risk.CorelationCoefficient.CC.Value : ExtractValue <decimal>(attribute[4]))); case (int)Risk.CalcType.BetaCoefficient: return(Risk.BetaCoefficient.Calculate((attribute[0] == "0") ? Risk.PortfolioCovariation.PC.Value : ExtractValue <decimal>(attribute[0]), (attribute[1] == "0") ? (decimal)Math.Pow((double)Risk.StandardDeviation.sD.Value, 2) : ExtractValue <decimal>(attribute[1]))); } } #endregion #region Deprication else if (spinner[0] == (int)Calculate.Deprication) { switch (spinner[1]) { case (int)Deprication.DepricationType.Linear: if (spaces == 2) { return(Deprication.LinearDeprication.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <int>(attribute[2]))); } if (spaces == 3) { return(Deprication.LinearDeprication.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <int>(attribute[2]), ExtractValue <decimal>(attribute[3]))); } break; case (int)Deprication.DepricationType.DecreasingDeduction: return(Deprication.DecreasingDeduction.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <int>(attribute[2]), ExtractValue <decimal>(attribute[3]))); case (int)Deprication.DepricationType.ComulativeMethod: return(Deprication.ComulativeMethod.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <int>(attribute[2]))); case (int)Deprication.DepricationType.EqualDegression: return(Deprication.ComulativeMethod.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <int>(attribute[2]))); } } #endregion #region Annuity else if (spinner[0] == (int)Calculate.Annuity) { switch (spinner[1]) { case (int)Annuity.PresentOrFuture.Future: return(spaces == 3 ? Annuity.FutureValue.Calculate(ExtractValue <int>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <decimal>(attribute[2]), ExtractValue <double>(attribute[3])) : Annuity.FutureValue.Calculate(ExtractValue <int>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <decimal>(attribute[2]), ExtractValue <double>(attribute[3]), ExtractValue <double>(attribute[4]), (Interest.InterestPeriods)ExtractValue <int>(attribute[5]))); case (int)Annuity.PresentOrFuture.Present: return(spaces == 3 ? Annuity.PresentValue.Calculate(ExtractValue <int>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <decimal>(attribute[2]), ExtractValue <double>(attribute[3])) : Annuity.PresentValue.Calculate(ExtractValue <int>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <decimal>(attribute[2]), ExtractValue <double>(attribute[3]), ExtractValue <double>(attribute[4]), (Interest.InterestPeriods)ExtractValue <int>(attribute[5]))); } } #endregion #region Stock and Bond price else if (spinner[0] == (int)Calculate.StockAndBondPrices) { switch (spinner[1]) { case (int)StockAndBondPrices.CalcType.BondYield: return(attribute[2] == "1" ? StockAndBondPrices.BondYield.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1])) : StockAndBondPrices.BondYield.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <int>(attribute[2]))); case (int)StockAndBondPrices.CalcType.PresentDiscountBondPrice: return(StockAndBondPrices.PresentDiscountBondPrice.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <decimal>(attribute[2]), ExtractValue <int>(attribute[3]))); case (int)StockAndBondPrices.CalcType.CuponBondPrice: return(StockAndBondPrices.CuponBondPrice.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <decimal>(attribute[2]), ExtractValue <int>(attribute[3]))); case (int)StockAndBondPrices.CalcType.PerpetuityPrice: return(StockAndBondPrices.PerpetuityPrice.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), attribute.Length < 3 ? 0 : ExtractValue <decimal>(attribute[2]))); case (int)StockAndBondPrices.CalcType.PreferredStockPrice: return(StockAndBondPrices.PreferredStockPrice.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]))); case (int)StockAndBondPrices.CalcType.CommonSharePrice: return(StockAndBondPrices.CommonSharePrice.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <decimal>(attribute[2]), attribute.Length == 4 ? ExtractValue <int>(attribute[3]) : 0)); case (int)StockAndBondPrices.CalcType.RateOfIncreasing: return(StockAndBondPrices.RateOfIncreasing.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <decimal>(attribute[2]))); } } #endregion #region Asset Investment else if (spinner[0] == (int)Calculate.AssetInvestment) { switch (spinner[1]) { case (int)AssetInvestment.AssetValues.NetCashFlows: return(AssetInvestment.NetCashFlows.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <decimal>(attribute[2]), ExtractValue <decimal>(attribute[3]), ExtractValue <decimal>(attribute[4]))); case (int)AssetInvestment.AssetValues.AverageIncomeNorm: decimal[] netIncomeEA = new decimal[ExtractValue <int>(attribute[1])]; for (int i = 0; i < ExtractValue <int>(attribute[1]); i++) { netIncomeEA[i] = ExtractValue <decimal>(attribute[i + 2]); } return(AssetInvestment.AverageIncomeNorm.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <int>(attribute[1]), netIncomeEA)); case (int)AssetInvestment.AssetValues.NetPresentValue: decimal[] cashFlowsEA = new decimal[ExtractValue <int>(attribute[2])]; for (int i = 0; i < ExtractValue <int>(attribute[2]); i++) { cashFlowsEA[i] = ExtractValue <decimal>(attribute[i + 3]); } return(AssetInvestment.NetPresentValue.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <int>(attribute[2]), cashFlowsEA)); case (int)AssetInvestment.AssetValues.ProfitabilityIndex: cashFlowsEA = new decimal[ExtractValue <int>(attribute[2])]; for (int i = 0; i < ExtractValue <int>(attribute[2]); i++) { cashFlowsEA[i] = ExtractValue <decimal>(attribute[i + 3]); } return(AssetInvestment.ProfitabilityIndex.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <int>(attribute[2]), cashFlowsEA)); case (int)AssetInvestment.AssetValues.PaybackPeriod: cashFlowsEA = new decimal[ExtractValue <int>(attribute[2])]; for (int i = 0; i < ExtractValue <int>(attribute[2]); i++) { cashFlowsEA[i] = ExtractValue <decimal>(attribute[i + 3]); } return(AssetInvestment.PaybackPeriod.Calculate(ExtractValue <decimal>(attribute[0]), ExtractValue <decimal>(attribute[1]), ExtractValue <int>(attribute[2]), cashFlowsEA)); } } #endregion return(""); }
public string GetSolution() { return(Factors.GetPrimeFactors(600851475143).Max().ToString()); }
public void Get_Factorys_Of_1_Returns_1() { var result = Factors.GetFactors(1).ToList(); Assert.IsTrue(result.Contains(1)); }
/// <summary> /// Initializes a new instance of the <see cref="UserLU"/> class. This object will compute the /// LU factorization when the constructor is called and cache it's factorization. /// </summary> /// <param name="matrix">The matrix to factor.</param> /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException">If <paramref name="matrix"/> is not a square matrix.</exception> public UserLU(Matrix <float> matrix) { if (matrix == null) { throw new ArgumentNullException("matrix"); } if (matrix.RowCount != matrix.ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSquare); } // Create an array for the pivot indices. var order = matrix.RowCount; Factors = matrix.Clone(); Pivots = new int[order]; // Initialize the pivot matrix to the identity permutation. for (var i = 0; i < order; i++) { Pivots[i] = i; } var vectorLUcolj = new float[order]; for (var j = 0; j < order; j++) { // Make a copy of the j-th column to localize references. for (var i = 0; i < order; i++) { vectorLUcolj[i] = Factors.At(i, j); } // Apply previous transformations. for (var i = 0; i < order; i++) { var kmax = Math.Min(i, j); var s = 0.0f; for (var k = 0; k < kmax; k++) { s += Factors.At(i, k) * vectorLUcolj[k]; } vectorLUcolj[i] -= s; Factors.At(i, j, vectorLUcolj[i]); } // Find pivot and exchange if necessary. var p = j; for (var i = j + 1; i < order; i++) { if (Math.Abs(vectorLUcolj[i]) > Math.Abs(vectorLUcolj[p])) { p = i; } } if (p != j) { for (var k = 0; k < order; k++) { var temp = Factors.At(p, k); Factors.At(p, k, Factors.At(j, k)); Factors.At(j, k, temp); } Pivots[j] = p; } // Compute multipliers. if (j < order & Factors.At(j, j) != 0.0) { for (var i = j + 1; i < order; i++) { Factors.At(i, j, (Factors.At(i, j) / Factors.At(j, j))); } } } }
public void Dispose() { Factors.Dispose(); }
public void VerifyInitalization() { Assert.IsNotNull(Factors.ForUser(_userAccount)); }
public void GetPrimeFactors_SupportedValueGiven_ReturnsCorrectSizeArray() { int[] results = Factors.GetPrimeFactors(10); Assert.That(results.Length, Is.EqualTo(3)); }
public void GetPrimeFactors_TooSmallValueGiven_ThrowsExeption() { Assert.Throws <ArgumentOutOfRangeException>(() => Factors.GetPrimeFactors(0)); }
public void GetPrimeFactors_SupportedValueGiven_ReturnsArrayOfFactors() { int[] results = Factors.GetPrimeFactors(10); Assert.That(results, Is.EquivalentTo(new int[] { 1, 2, 5 })); }
public void GetAllFactors_SupportedValueGiven_ReturnsArrayOfFactors(int baseNumber, int[] expectedResult) { int[] result = Factors.GetAllFactors(baseNumber); Assert.That(result, Is.EquivalentTo(expectedResult)); }
static void Main(string[] args) { /* * The sequence of triangle numbers is generated by adding the natural numbers. * So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. * * The first ten terms would be: * 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... * * Let us list the factors of the first seven triangle numbers: * * 1: 1 * 3: 1,3 * 6: 1,2,3,6 * 10: 1,2,5,10 * 15: 1,3,5,15 * 21: 1,3,7,21 * 28: 1,2,4,7,14,28 * We can see that 28 is the first triangle number to have over five divisors. * * What is the value of the first triangle number to have over five hundred divisors? * Answer: 76576500 */ Stopwatch timer = new Stopwatch(); Console.WriteLine("Find the first Triangular Number with at least the specified number of divisors."); Console.WriteLine("--------------------------------------------------------------------------------"); Console.WriteLine(); Console.Write("How many divisors do you want? "); int divisorsWanted = int.Parse(Console.ReadLine()); int triangularNumber = 3; int triangularNumberValue = 0; bool hasRequiredDivisors = false; int mostDivisors = 0; timer.Start(); while (!hasRequiredDivisors) { triangularNumber++; triangularNumberValue = TriangularNumbers.GetNthTriangular(triangularNumber); int divisors = Factors.GetAllFactors(triangularNumberValue).Length; if (divisors > mostDivisors) { mostDivisors = divisors; } if (divisors >= divisorsWanted) { hasRequiredDivisors = true; } } timer.Stop(); Console.WriteLine("The first Triangular Number with {0} divisors is ({1}) {2}", divisorsWanted, triangularNumber, triangularNumberValue); Console.WriteLine(timer.Elapsed); Console.ReadLine(); }
public static void DefaultFunction() { Function = p => Factors.Sum(f => Formula(f)(p)); }
public override object Run(RunModes runMode, object input, bool Logging) { return(Factors.GetFactors((long)input).Where(fac => Primes.IsPrime((long)fac)).Max()); }