public void TestError() { var tokenSource = new CancellationTokenSource(); const int initialState = 42; const int totalIterations = 10; var ibw = RecursiveBackgroundWorker.Make ( initialState, (i, c) => { Thread.Sleep(10); return(IterationResult.Make(i + 1, ProgressStatus.Error)); }, totalIterations, tokenSource ); var nextResult = initialState; ibw.OnIterationResult.Subscribe( r => { nextResult = r.Data; }); ibw.Start(); Thread.Sleep(100); Assert.AreEqual(ibw.CurrentState, nextResult); Assert.AreEqual(ibw.CurrentState, initialState); Assert.AreEqual(ibw.CurrentIteration, 0); }
public string Decrypt(string text, string key) { var textBlocks = Get64BitBlocks(text); var superKey = Get64BitBlocks(key).First(); for (var i = 0; i < textBlocks.Count; i++) { var l = GetLeftSubBlock(textBlocks[i]); var r = GetRightSubBlock(textBlocks[i]); var iterationResult = new IterationResult() { LeftSubBlock = l, RightSubBlock = r }; for (var iteration = NumberOfIterations; iteration >= 1; iteration--) { iterationResult = PerformIteration(l, r, superKey, iteration); l = iterationResult.RightSubBlock; r = iterationResult.LeftSubBlock; } textBlocks[i] = JoinSubBlocks(iterationResult.LeftSubBlock, iterationResult.RightSubBlock); } return(GetTextFromBlocks(textBlocks)); }
/// <summary> /// Iterate over an area of the bitmap, calling the specified function for each pixel. Function must be defined as /// void Func(int x, int y, byte a, byte r, byte g, byte b, int index, IterationResult itres) /// </summary> public static void IterateOver(this Bitmap bmp, Rectangle rect, Action <int, int, byte, byte, byte, byte, int, IterationResult> p) { // Lock the bitmap's bits. var bmprect = new Rectangle(0, 0, bmp.Width, bmp.Height); rect = Rectangle.Intersect(rect, bmprect); BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. int bytes = bmpData.Stride * rect.Height; //if (_rgbValues == null || _rgbValues.Length < bytes) { // _rgbValues = new byte[bytes]; //} byte[] rgbValues = new byte[bytes]; // Copy the RGB values into the array. Marshal.Copy(ptr, rgbValues, 0, bytes); //int count = 0; int stride = bmpData.Stride; bool changedSomething = false; var itres = new IterationResult(); rect = Rectangle.Intersect(rect, bmprect); int i = 0; for (int y = 0; y < rect.Height; y++) { for (int x = 0; x < rect.Width; x++) { byte b = rgbValues[(y * stride) + (x * 4)]; byte g = rgbValues[(y * stride) + (x * 4) + 1]; byte r = rgbValues[(y * stride) + (x * 4) + 2]; byte a = rgbValues[(y * stride) + (x * 4) + 3]; p(x + rect.Left, y + rect.Top, a, r, g, b, i++, itres.Reset()); if (itres.Color != null) { changedSomething = true; var color = itres.Color.Value; rgbValues[(y * stride) + (x * 4)] = color.B; rgbValues[(y * stride) + (x * 4) + 1] = color.G; rgbValues[(y * stride) + (x * 4) + 2] = color.R; rgbValues[(y * stride) + (x * 4) + 3] = color.A; } if (itres.Abort) { break; } } if (itres.Abort) { break; } } if (changedSomething) { Marshal.Copy(rgbValues, 0, ptr, bytes); } bmp.UnlockBits(bmpData); }
/// <summary> /// Trigger every event after the actual step /// Trigger Agent.SetResults() /// </summary> public void PostStep() { AgentNetwork.AllAgents().ToList().ForEach(a => a.PostStep()); Messages.ClearMessagesSent(Schedule.Step); IterationResult.SetResults(); Schedule.Step++; }
public void solve(double tolerance, double step_size = 0.35, int iter_limit = 100) { if (!checkInitPoint(tolerance, x)) { prepareInitData(); while (iter_limit > 0) { IterationResult res = iterate_internal(Ainit, cinit, xinit, tolerance, step_size); iter_limit--; if (res == IterationResult.Unbounded) { return; } if (res == IterationResult.Optimal /* || checkInitPoint(tolerance, xinit)*/) { break; } } update_x(); } while (iter_limit > 0) { IterationResult res = iterate_internal(A, c, x, tolerance, 0.9); iter_limit--; if (res != IterationResult.Descended) { return; } } }
public void TestCancel() { var tokenSource = new CancellationTokenSource(); var inputs = new[] { 42, 43, 44, 45 }; var ibw = EnumerativeBackgroundWorker.Make ( inputs, (i, c) => IterationResult.Make(i + 1, ProgressStatus.StepComplete) ); var nextResult = 0; ibw.OnIterationResult.Subscribe( r => { nextResult = r.Data; tokenSource.Cancel(); }); ibw.Start(tokenSource); Thread.Sleep(100); Assert.IsTrue(ibw.CurrentOutput < 46); Assert.IsTrue(ibw.CurrentIteration < inputs.Length); Assert.AreEqual(ibw.CurrentOutput, nextResult); }
public async Task OnRunAsync(CancellationTokenSource cancellationTokenSource) { var rbw = EnumerativeBackgroundWorker.Make ( inputs: SorterGenomeEvalGridVmInitial.SorterGenomeEvalVms .Select( ev => new Tuple <ISorterGenomeEval, ISorterMutateParams> ( ev.SorterGenomeEval, SorterMutateParamsVm.GetParams )), mapper: (s, c) => { return(IterationResult.Make ( data: s.Item1.ToSgMutantProfile(s.Item2), progressStatus: ProgressStatus.StepComplete )); } ); Busy = true; //_cancellationTokenSource = cancellationTokenSource; rbw.OnIterationResult.Subscribe(UpdateSorterMutateResults); await rbw.Start(cancellationTokenSource); Busy = false; }
/// <summary> /// Raises the event <see cref="IterationCompleted"/>, stating that an iteration was performed. /// </summary> /// <param name="currentIteration">The current iteration of the evaluation.</param> /// <param name="currentEvaluation">The current running evaluation.</param> protected virtual void OnIterationCompleted(IterationResult currentIteration, EvaluationResult currentEvaluation) { if (IterationCompleted != null) { IterationCompleted(this, new IterationEventArgs(currentIteration, currentEvaluation)); } }
/// <summary> /// Validates ILoadTest scenario correctness by executing single test iteration /// from ScenarioSetup to ScenarioTearDown on the same thread. /// Exceptions are not handled on purpose to ease problem identification while developing. /// </summary> /// <param name="loadTestScenario">ILoadTestScenario object</param> /// <param name="threadId">TheardId to set in TestContext</param> /// <param name="threadIterationId">ThreadIterationId to set in TestContext</param> /// <param name="globalIterationId">GlobalIterationId to set in TestContext</param> /// <returns>Raw result from single iteration</returns> public static IterationResult Validate(ILoadTestScenario loadTestScenario, int threadId = 0, int threadIterationId = 0, int globalIterationId = 0) { ExecutionTimer timer = new ExecutionTimer(); TestContext testContext = new TestContext(threadId, timer); testContext.Reset(-1, -1); loadTestScenario.ScenarioSetup(testContext); testContext.Reset(threadIterationId, globalIterationId); testContext.Checkpoint(Checkpoint.IterationSetupCheckpointName); loadTestScenario.IterationSetup(testContext); testContext.Checkpoint(Checkpoint.IterationStartCheckpointName); testContext.Start(); loadTestScenario.ExecuteScenario(testContext); testContext.Stop(); testContext.Checkpoint(Checkpoint.IterationEndCheckpointName); testContext.Checkpoint(Checkpoint.IterationTearDownCheckpointName); loadTestScenario.IterationTearDown(testContext); IterationResult result = new IterationResult(testContext); testContext.Reset(-1, -1); loadTestScenario.ScenarioTearDown(testContext); return(result); }
public ExampleEnvironment() { IterationResult.Off(); IterationResult.Tasks.On = true; IterationResult.Messages.On = true; SetDebug(false); }
public void Initialize() { _result = new IterationResult(Environment); _specificResult = new TestResult(); _result.Add(_specificResult); _result.Off(); _result.SetFrequency(TimeStepType.Daily); }
private async void _validateButton_Click(object sender, EventArgs e) { IterationResult result = await Task.Run(() => _validator.Validate(0)).ConfigureAwait(false); Invoke(new InvokeDelegate( () => AppendMessage($"Validation OK:\r\n{String.Join("\r\n", Process(result).Select(c => $"{c.Item1}->{c.Item2}: {c.Item3}{(c.Item4 != null ? $"\r\n{c.Item4.ToString()}\r\n" : "")}"))}")) ); }
private void ExecutorThread_ThreadFailed(TestExecutorThread sender, IterationResult result, Exception ex) { if (!_disposing) { TryRemoveThread(sender.ThreadId); _threadErrors.Add(ex); } }
public void IterateTest() { Assert.DoesNotThrow(() => { BeginTest(TestEnv0, 4); }); List <int> integers = new List <int>() { 1, 2, 3, 4, 5 }; TaskInfo iterateTask = new TaskInfo { TaskType = TaskType.EvalExpression, Expression = ExpressionInfo.Iterate(integers), OutputsCount = 1, }; TaskInfo sequence = new TaskInfo { TaskType = TaskType.Sequence, Children = new[] { iterateTask, } }; sequence.SetParents(); const int playerId = 1; bool isIterated = false; BeginCleanupCheck(playerId); FinializeTest(playerId, sequence, result => { Assert.IsTrue(isIterated); Assert.AreEqual(TaskState.Completed, result.State); Assert.IsFalse(result.IsFailed); CleanupCheck(playerId); Assert.Pass(); }, childTask => { if (childTask.State == TaskState.Completed) { ITaskMemory memory = m_engine.GetTaskEngine(playerId).Memory; IterationResult iterResult = (IterationResult)memory.ReadOutput(iterateTask.Parent.TaskId, iterateTask.TaskId, 0); Assert.IsFalse(iterResult.IsLast); Assert.AreEqual(1, (int)iterResult.Object); isIterated = true; } }); }
/// <summary> /// override : use to set specific PostProcessResult parameter /// </summary> public virtual IterationResult SetIterationResult(ushort iterationNumber) { IterationResult.Iteration = iterationNumber; IterationResult.Step = Schedule.Step; var scenarii = GetAllStoppedScenarii(); IterationResult.Success = scenarii.All(s => s.Success); //IterationResult.HasItemsNotDone = scenarii.Exists(s => s.IterationResult.HasItemsNotDone); //IterationResult.NotFinishedInTime = scenarii.Exists(s => s.IterationResult.NotFinishedInTime); //IterationResult.SeemsToBeBlocked = scenarii.Exists(s => s.IterationResult.SeemsToBeBlocked); return(IterationResult.Clone()); }
public FinalResult GetMinimum(InitialData data) { _func = data.Func; _iterationCount = 0; _result = new FinalResult { Results = new List <IterationResult>() }; if (_method == FibonacciMethod) { GenerateFibonacci((long)((data.To - data.From) / _error)); } var segment = new Segment { From = data.From, To = data.To }; _x = _v = _w = segment.Mid; _d = _e = segment.Length; _brantError = _error / 1000; _initialSegment = new Segment() { From = segment.From, To = segment.To }; _lastIterationResult = new IterationResult { Segment = _initialSegment }; _result.Results.Add(new IterationResult { Segment = segment, From = segment.From, To = segment.To, LengthRatio = segment.Length / _initialSegment.Length, Res1 = _func(segment.From), Res2 = _func(segment.To) }); while (segment.Length >= _error) { _iterationCount++; segment = _method(segment); _result.Results.Add(_lastIterationResult); } _result.IterationCount = _iterationCount; _result.Res = Math.Min(_func(segment.From), _func(segment.To)); return(_result); }
public void Should_return_next_iteration_step_from_previous_iteration_result() { var previousIterationResult = new IterationResult { IterationStep = 1 }; const int expectedIterationStep = 2; var actionResult = controller.GetNextStep(previousIterationResult); var okResult = actionResult as OkObjectResult; var iterationResult = okResult.Value as IterationResult; iterationResult.IterationStep.Should().Be(expectedIterationStep); }
public void Should_set_algorithm_type_to_iteration_result_from_previous_iteration_result() { var previousIterationResult = new IterationResult { AlgorithmType = ChoiceTransportAlgorithmType.Deviation }; var actionResult = controller.GetNextStep(previousIterationResult); var okResult = actionResult as OkObjectResult; var iterationResult = okResult.Value as IterationResult; iterationResult.AlgorithmType.Should().Be(iterationResult.AlgorithmType); }
public void TestCtor() { var inputs = new[] { 42, 43, 44, 45 }; var ibw = EnumerativeBackgroundWorker.Make ( inputs, (i, c) => IterationResult.Make(i + 1, ProgressStatus.StepComplete) ); Assert.AreEqual(ibw.CurrentInput, inputs[0]); Assert.AreEqual(ibw.CurrentIteration, 0); Assert.AreEqual(ibw.TotalIterations, inputs.Count()); }
public void Should_return_average_satisfaction_from_transport_system_satisfaction() { const int satisfaction = 1; var previousResult = new IterationResult(); transportSystemSatisfaction.Evaluate(Arg.Any <PassengerDto[]>()) .Returns(satisfaction); var actionResult = controller.GetNextStep(previousResult); var okResult = actionResult as OkObjectResult; var iterationResult = okResult.Value as IterationResult; iterationResult.AverageSatisfaction.Should().Be(satisfaction); }
/// <summary> /// Initialize model : /// clear Agents and create/Add all agents of the model /// called by Engine.InitializeIteration /// </summary> public virtual void InitializeIteration() { AgentNetwork.AgentIndex = 1; Messages.Clear(); //At this point, we must use Environment.Organization.MetaNetwork and not Organization.MetaNetwork MainOrganization = MainOrganizationReference.Clone(); AgentNetwork.Clear(); IterationResult.Initialize(); SysDynEngine.Clear(); SysDynEngine.Initialize(); SetAgents(); // Intentionally after SetAgents //InitializeInteractionNetwork(); AgentNetwork.SetStarted(); }
public IActionResult GetNextSteps([FromBody] IterationResult previousIterationResult, [FromQuery] int countSteps = 100) { var result = new List <IterationResult>(); var currentStep = previousIterationResult; for (var i = 0; i < countSteps; i++) { var nextStep = GetNextIterationResult(currentStep); result.Add(nextStep); currentStep = nextStep; } return(Ok(result)); }
private IterationResult GetNextIterationResult(IterationResult previousIterationResult) { var allPassengers = passengersFactory .CreatePassengers(previousIterationResult.AlgorithmType, previousIterationResult.Passengers); transportSystem.MakeIteration(allPassengers, previousIterationResult.AvailableTransportTypes); var passengerDtos = allPassengers .Select(x => x.ToPassengerDto()) .ToArray(); var averageSatisfaction = transportSystemSatisfaction.Evaluate(passengerDtos); var nextStep = previousIterationResult.Next(passengerDtos, averageSatisfaction); return(nextStep); }
public void Start() { values_ = new List <IAssessmentValue>(); instance_ = this; if (GlobalAttributes != "") { GlobalWatchValue = gameObject.AddComponent <AssessmentWatchValue>(); GlobalWatchValue.Attributes = GlobalAttributes; GlobalWatchValue.Internal = true; } try { Debug.Log("Connecting to WebService"); evalService_ = new EvaluationService(AssessmentUrl, AssignmentFileName); Debug.Log("Got ID: " + evalService_.ContextID); Enabled = true; //var ev = GameEventBuilder.EnterSection(FirstSectionName); var ev = new GameEvent().Add( new PlayerAction() { Name = "EnterSection", Parameters = new ActionParameter[] { new ActionParameter() { Name = "section_class", Value = FirstSectionName } } } ); IterationResult result = Send(ev); if (OnEnteredSection != null) { OnEnteredSection(result); } } catch (Exception e) { Enabled = false; Debug.Log("WARNING! An error happened while connection to the Assessment service: " + e.Message); return; } }
async Task GenerateSamples() { Busy = true; var samplerParams = GetSorterSamplerParams(KeyCount.Value); _stopwatch.Reset(); _stopwatch.Start(); _cancellationTokenSource = new CancellationTokenSource(); var rando = Rando.Fast(Seed.Value); var inputs = Enumerable.Range(0, 10000).Select(t => rando.NextInt()); IEnumerativeBackgroundWorker <int, SorterSamplerResults> ibw = EnumerativeBackgroundWorker.Make ( inputs: inputs, mapper: (i, c) => { var sorterSamplerResults = SorterRandomSampler.SorterSampler( keyCount: KeyCount.Value, switchCount: samplerParams.SwitchCount, histogramMin: samplerParams.HistogramMin, histogramMax: samplerParams.HistogramMax, seed: i, repCount: ReportFrequency.Value, lowRangeMax: LowRangeMax.Value, highRangeMin: HighRangeMin.Value, cancellationToken: _cancellationTokenSource.Token ); if (sorterSamplerResults.WasCancelled) { return(IterationResult.Make(default(SorterSamplerResults), ProgressStatus.StepIncomplete)); } return(IterationResult.Make(sorterSamplerResults, ProgressStatus.StepComplete)); } ); ibw.OnIterationResult.Subscribe(UpdateSorterSamplerResults); await ibw.Start(_cancellationTokenSource); Busy = false; _stopwatch.Stop(); CommandManager.InvalidateRequerySuggested(); }
public async Task OnRunAsync(CancellationTokenSource cancellationTokenSource) { Busy = true; _cancellationTokenSource = cancellationTokenSource; var rando = Rando.Fast(ScpParamsVm.Seed); var rbw = RecursiveBackgroundWorker.Make ( initialState: ScpWorkflow.Make ( sorterLayer: SorterLayer.Make( sorterGenomes: _sorterGenomeEvals.Select(e => e.Value.SorterGenome), generation: ScpParamsVm.CurrentGeneration ), scpParams: ScpParamsVm.GetParams, generation: ScpParamsVm.CurrentGeneration ), recursion: (i, c) => { var nextStep = i; while (true) { if (_cancellationTokenSource.IsCancellationRequested) { return(IterationResult.Make <IScpWorkflow>(null, ProgressStatus.StepIncomplete)); } nextStep = nextStep.Step(rando.NextInt()); if (nextStep.CompWorkflowState == CompWorkflowState.ReproGenomes) { return(IterationResult.Make(nextStep, ProgressStatus.StepComplete)); } } }, totalIterations: ScpParamsVm.TotalGenerations - ScpParamsVm.CurrentGeneration, cancellationTokenSource: _cancellationTokenSource ); rbw.OnIterationResult.Subscribe(UpdateSorterTuneResults); await rbw.Start(); Busy = false; }
public void OnIterationFinished(IterationResult result) { _loss += result.Loss; _accuracy += result.Accuracy; _elapsed += result.IterationTime.Milliseconds; Console.SetCursorPosition(0, (result.Epoch - 1) * 2); Console.Write($"{result.Epoch}/{result.EpochsCount}"); DrawProgressBar(result.Iteration, result.ExamplesPerEpoch); Console.Write(" - "); Console.Write($"{_elapsed / result.Iteration} ms/step"); Console.Write(" - "); Console.Write($"metric: {_accuracy / result.Iteration:0.0000}"); Console.Write(" - "); Console.Write($"loss: {_loss / result.Iteration:0.0000}"); }
public void TestCtor() { var tokenSource = new CancellationTokenSource(); const int initialState = 42; const int totalIterations = 10; var ibw = RecursiveBackgroundWorker.Make ( initialState, (i, c) => IterationResult.Make(i + 1, ProgressStatus.StepComplete), totalIterations, tokenSource ); Assert.AreEqual(ibw.CurrentState, initialState); Assert.AreEqual(ibw.CurrentIteration, 0); Assert.AreEqual(ibw.TotalIterations, totalIterations); }
public void Should_call_make_iteration_for_transport_system() { var prevIterationResult = new IterationResult { AlgorithmType = ChoiceTransportAlgorithmType.Deviation, IterationStep = 1, AverageSatisfaction = 1, Passengers = new PassengerDto[0], AvailableTransportTypes = AvailableTransportTypes }; var allPassengers = new Passenger[0]; passengersFactory.CreatePassengers(prevIterationResult.AlgorithmType, prevIterationResult.Passengers) .Returns(allPassengers); var _ = controller.GetNextStep(prevIterationResult); transportSystem.Received().MakeIteration(allPassengers, AvailableTransportTypes); }
public IterationDataSource(string rootDir, string iterFolder) { string resultFile = Path.Combine(iterFolder, Constants.ResultJsonName); Debug.Assert(File.Exists(resultFile)); IterationResult iter = JsonConvert.DeserializeObject <IterationResult>(File.ReadAllText(resultFile)); string traceFile = Path.Combine(rootDir, iter.TracePathLocation); Debug.Assert(File.Exists(traceFile)); // we have to unzip the trace that PerfView collected. Normally // PerfView does it, but since we're not using PerfView to read // the data we collected we're stuck doing it ourselves. string unzippedEtlPath = Path.Combine(iterFolder, Constants.UnzippedTraceName); Logger.LogVerbose($"Unzipping trace {traceFile}"); ZipFile.ExtractToDirectory(traceFile, unzippedEtlPath); // traceFile has a .etl.zip extensions, and we're looking for a file with a .etl // extension in the unzipped ETL path. string strippedFilename = Path.GetFileNameWithoutExtension(traceFile); Logger.LogVerbose("Parsing ETW events"); var source = new ETWTraceEventSource(Path.Combine(unzippedEtlPath, strippedFilename)); m_source = source; source.NeedLoadedDotNetRuntimes(); Logger.LogVerbose("Calculating GC stats"); source.Process(); Trace = source.Processes() // TODO(segilles) this isn't quite right, it's possible (but HIGHLY unlikely) // that we could collide pids. .First(t => t.ProcessID == iter.Pid) .LoadedDotNetRuntime(); TraceLocation = iter.TracePathLocation; DurationMsec = iter.DurationMsec; ExitCode = iter.ExitCode; }
// Performs a single iteration over the coefficients. Returns the results of the iteration as well as stores them in the internal list // Will simply return the very last iteration result if all the roots have been found / no more roots need to be found via iterations public IterationResult performIteration() { IterationResult res = new IterationResult(); if(roots.Length - foundRootCount > 2) { //if there are more than two roots left to find, perform a generic iteration step res = performIterationStep(); } else if(roots.Length - foundRootCount == 2) { //if there are exactly 2 roots left to find, perform quadratic solution res = performQuadraticSolution(); } else if(roots.Length - foundRootCount == 1) { //if only one root left, calculate it using the subroutine solveSingle (and store it) and set dataRelevant to false roots[foundRootCount++] = solveSingle(coefficients[coefficients.Count-1][0], coefficients[coefficients.Count - 1][1]); res.dataRelevant = false; res.rootFound = true; } else { //all the roots have been found, set dataRelevant to false and set allRootsFound to true; res.allRootsFound = true; res.dataRelevant = false; } if (roots.Length - foundRootCount == 0) { //make sure allRootsFound is set to true; res.allRootsFound = true; } return res; }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //PRIVATE METHOD DEFINITIONS //This performs a single, actual iteration of Bairstow's method private IterationResult performIterationStep() { IterationResult result = new IterationResult(); result.dataRelevant = true; //set up the arrays double[] aArray = coefficients[coefficients.Count - 1]; double[] bArray = new double[aArray.Length]; double[] cArray = new double[bArray.Length]; //set up the r and s variables double r = startR; double s = startS; List<IterationResult> currSet = iterResults[iterResults.Count - 1]; if (currSet.Count != 0) //is there current information for this iteration set { //if so, set up the r and s using the previous specified values IterationResult prev = currSet[currSet.Count - 1];//iterResults[overIterNum][iterNum - 1]; r = prev.iterR + prev.deltaR; s = prev.iterS + prev.deltaS; } else if(foundRootCount > 0) //have we found any roots { //if so, use the previous 2 values of r and s as good starting values of r and s List<IterationResult> prevSet = iterResults[iterResults.Count - 2]; IterationResult lastOfPrev = prevSet[prevSet.Count - 1]; r = lastOfPrev.iterR + lastOfPrev.deltaR; s = lastOfPrev.iterS + lastOfPrev.deltaS; } if(currSet.Count >= maxIterNum) { result.maxIterationsExceeded = true; throw new MAX_ITER_NUM_REACHED_EXCEPTION(); } //calculate the bArray and cArray values bArray[bArray.Length - 1] = aArray[bArray.Length - 1]; bArray[bArray.Length - 2] = aArray[aArray.Length - 2] + r * bArray[bArray.Length - 1]; cArray[bArray.Length - 1] = bArray[bArray.Length - 1]; cArray[bArray.Length - 2] = bArray[bArray.Length - 2] + r * cArray[bArray.Length - 1]; for(int i = bArray.Length - 3; i >= 0; --i) { bArray[i] = aArray[i] + r * bArray[i + 1] + s * bArray[i + 2]; cArray[i] = bArray[i] + r * cArray[i + 1] + s * cArray[i + 2]; } //calculate the deltas for the next iteration double deltaS = 0; double deltaR = 0; { int count = currSet.Count; int bob = 1; //assign some values for convenience double c1 = cArray[1]; double c2 = cArray[2]; double c3 = cArray[3]; double b1 = bArray[1]; double b0 = bArray[0]; //solve a system of two equations for deltaS and deltaR // c2 * deltaR + c3 * deltaS = -b1 // c1 * deltaR + c2 * deltaS = -b0 //bad solution that involved maybe dividing by 0 //ds = ( ( -c1 * b1 / c2 ) + b0) / ( ( c1 * c3 / c2 ) - c2) //deltaS = (((0 - c1) * b1 / c2) + b0) / ( ( c1 * c3 / c2 ) - c2 ); //(-b1 - c3 * ds) / c2 = dr //deltaR = ((0 - b1) - c3 * deltaS) / c2; //here we go matrices double one_one, one_two, one_three, two_one, two_two, two_three, store_meh; one_one = c2; one_two = c3; one_three = -b1; two_one = c1; two_two = c2; two_three = -b0; //Current state of the matrix //[c2 c3 -b1] //[c1 c2 -b0] // //[1-1 1-2 1-3] //[2-1 2-2 2-3] //from here on out, whenever i use num1 or num2 or num3 or .. in a matrix, i'm just referring to some number, not a specific number from a previous diagram //when i use a numX in an english statement, assume im referring to the diagram directly above //add the bottom row to the top and the top to the bottom in hopes of getting rid of all 0s { bool good = false; double temp_one = 0, temp_two = 0, temp_three = 0, mult = 1; //add some multiple of the bottom row to the top while (!good) { temp_one = one_one + two_one * mult; temp_two = one_two + two_two * mult; temp_three = one_three + two_three * mult; good = (temp_one != 0) && (temp_two != 0); //make sure neither of the important two are 0 ++mult; } one_one = temp_one; one_two = temp_two; one_three = temp_three; good = false; mult = 0; //because we may not have to actually add anything to make the bottom happy //add some multiple of the top row to the bottom while (!good) { temp_one = one_one * mult + two_one; temp_two = one_two * mult + two_two; temp_three = one_three * mult + two_three; good = (temp_one != 0) && (temp_two != 0); //make sure neither of the important two are 0 ++mult; } two_one = temp_one; two_two = temp_two; two_three = temp_three; } /* //old, bad code for the above code one_one += two_one; one_two += two_two; one_three += two_three; //add the top row to the bottom two_one += one_one; two_two += one_two; two_three += one_three; */ //hopefully, every cell has something in it (otherwise I may be screwed...) //store one_one and divide that row by it to get //[1 num1 num2] store_meh = one_one; one_one = one_one / store_meh; one_two = one_two / store_meh; one_three = one_three / store_meh; //current state is below //[1 num1 num2] //[num3 num4 num5] //subtract num3 from num 3, num1 * num 3 from num4, and num2 * num3 from num5 //yields a bottom row of //[0 num1 num2] store_meh = two_one; two_one = 0; two_two -= (store_meh * one_two); two_three -= (store_meh * one_three); //current state is below //[1 num1 num2] //[0 num3 num4] //divide num3 by num3 to get 1 and num4 by num3 //yields a bottom row of //[0 1 num1] store_meh = two_two; two_two = 1; two_three = two_three / store_meh; //current state is below //[1 num1 num2] //[0 1 num3] //subtract num1 from itself and subtract (num3 * num1) from num2 //yields a top row of //[1 0 num1] store_meh = one_two; one_two = 0; one_three -= (store_meh * two_three); //current (and final) state is //[1 0 num1] //[0 1 num2] //so, deltaR = num1 and deltaS = num2 deltaR = one_three; deltaS = two_three; } //get the errors double sErr = /*make sure s isn't zero*/(s != 0) ? Math.Abs(deltaS / s) : (deltaS != 0) ? 1 : 0; //if s is zero and deltaS isn't, error should be 100%, otherwise we apparently nailed it head on double rErr = /*make sure r isn't zero*/(r != 0) ? Math.Abs(deltaR / r) : (deltaR != 0) ? 1 : 0; //if r is zero and deltaR isn't, error should be 100%, otherwise we apparently nailed it head on //assign all the relevant data result.iterR = r; result.iterS = s; result.iterRError = rErr; result.iterSError = sErr; result.deltaR = deltaR; result.deltaS = deltaS; //if latest error is beneath allowedError, calculate roots using solveRSQuadratic and store the data the roots array as well as update necessary instance variables //make sure to set res.rootFound to true; if (sErr < allowedError && rErr < allowedError) { result.rootFound = true; //make sure the result knows it found a root //solve for the roots and assign them Tuple<Tuple<double, double>, Tuple<double, double>> rootPair = solveRSQuadratic(r, s); roots[foundRootCount++] = rootPair.Item1; roots[foundRootCount++] = rootPair.Item2; //if there are more roots to be found, add another iterationresults list if(roots.Length - foundRootCount > 0) { iterResults.Add(new List<IterationResult>()); //calculate / assign the next set of coefficients //supposedly, the next set of coefficients already reside in bArray double[] nextSet = new double[aArray.Length - 2]; for(int i = 0; i < nextSet.Length; ++i) { nextSet[i] = bArray[i + 2]; } coefficients.Add(nextSet); } else { result.allRootsFound = true; } } //make sure to add the results to the correct iteration set if (!result.rootFound) iterResults[iterResults.Count - 1].Add(result); else iterResults[iterResults.Count - 2].Add(result); return result; }
//solves a (normal, not r/s) quadratic equation and stores the results in the roots table //this only happens if either the user submitted a quadratic to be solved or the highest power of x is even private IterationResult performQuadraticSolution() { IterationResult result = new IterationResult(); result.dataRelevant = false; result.rootFound = true; double[] currentEq = coefficients[coefficients.Count - 1]; //solve for the roots and assign them Tuple<Tuple<double, double>, Tuple<double, double>> rootPair = solveNormalQuadratic(currentEq[2], currentEq[1], currentEq[0]); roots[foundRootCount++] = rootPair.Item1; roots[foundRootCount++] = rootPair.Item2; if(roots.Length - foundRootCount == 0) { result.allRootsFound = true; } return result; }