private TGCVector3 RandomWaterSpawnLocation() { TGCVector3 spawnLocation = RandomSpawnLocation(); spawnLocation.Y = MathExtended.GetRandomNumberBetween((int)gameInstance.FloorLevelToWorldHeight(gameInstance.SueloDelMar.YMax), (int)gameInstance.WaterLevelToWorldHeight(-100)); return(spawnLocation); }
public static void AssertApprox(double a, double b, ErrorType errorType) { double maxError; if (!AllowErrors) { maxError = double.Epsilon; } else { switch (errorType) { case ErrorType.Distance: maxError = CalculateMaxDistanceErrorInMeters(); break; case ErrorType.Bearing: maxError = CalculateMaxBearingErrorInDegrees(); break; case ErrorType.DoubleComparison: maxError = double.Epsilon; break; default: throw new ArgumentOutOfRangeException(nameof(errorType), errorType, null); } } Assert.That(MathExtended.Approx(a, b, maxError, out var error), "expected: {0} result: {1} \n maxError: {2} error: {3} \n delta: {4}", a, b, maxError, error, error - maxError); }
private TGCVector3 RandomSpawnLocation() { Random random = new Random(); TGCVector3 spawnLocation = TGCVector3.Empty; spawnLocation.X = MathExtended.GetRandomNumberBetween(-gameInstance.BoundariesRadius, gameInstance.BoundariesRadius); spawnLocation.Y = MathExtended.GetRandomNumberBetween(-gameInstance.BoundariesRadius, gameInstance.BoundariesRadius); spawnLocation.Z = MathExtended.GetRandomNumberBetween(-gameInstance.BoundariesRadius, gameInstance.BoundariesRadius); return(spawnLocation); }
public void CalculateDestination_Bearing() { var origin = new Coordinates(0.0, 0.0, 0.0, AngleType.Degrees); var target = MathUtils.CalculateDestination(origin, TestUtils.DistanceInMeters, TestUtils.BearingInAngles); var calculatedBearing = MathUtils.BearingBetween(origin, target); var normalizedActualBearing = MathExtended.NormalizeDegrees(TestUtils.BearingInAngles); TestUtils.AssertApprox(normalizedActualBearing, calculatedBearing, TestUtils.ErrorType.Bearing); }
public override void Ejecutar() { var mcd = MathExtended.MinimoComunMultiplo( Calculadora.Resultado.Value, Valor.Value); var resultado = new KeyValuePair <int, int>( Calculadora.Resultado.Key * mcd / Calculadora.Resultado.Value - Valor.Key * mcd / Valor.Value, mcd); Calculadora.Actualizar(resultado); }
/// <summary> /// Zooms the map into/from the center (point of mouse) /// </summary> /// <param name="delta"></param> /// <param name="center"></param> private void ZoomMap(int delta, Point center) { if (firstZoom) { MapWidth = Map.Source.Width; MapHeight = Map.Source.Height; firstZoom = false; } var zoomfactor = ZoomFactor + delta / 120.0 / 10.0; ZoomFactor = MathExtended.Clamp(zoomfactor, ZOOM_MIN_CAP, ZOOM_MAX_CAP); Map.Width = MapWidth * ZoomFactor; Map.Height = MapHeight * ZoomFactor; }
public void Craft(Player crafter) { if (CanCraft(crafter)) { Item craftedItem = ItemDatabase.Instance.Generate(ProductId); RemoveRequirementsFrom(crafter); crafter.CollectItem(craftedItem); var craftingSounds = crafter.GameInstance.CraftingSounds; craftingSounds[MathExtended.GetRandomNumberBetween(0, craftingSounds.Count)].play(); } else { crafter.GameInstance.CraftingFailSound.play(); } }
public static int Forecast(ForecastOptions args, FileWriter writer, ILogger logger) { args.SeriesFileName = args.SeriesFileName ?? DefaultParams.seriesPath; args.ClustersDirectory = args.ClustersDirectory ?? DefaultParams.clustersPath; if (!File.Exists(args.SeriesFileName)) { logger.LogError("File with series {series} doesn't exist", args.SeriesFileName); return(1); } if (!Directory.Exists(args.ClustersDirectory)) { logger.LogError("Directory with clusters {clusters} doesn't exist", args.ClustersDirectory); return(1); } float[] series; using (var stream = new StreamReader(args.SeriesFileName)) { series = ServiceStack.Text.JsonSerializer.DeserializeFromReader <float[]>(stream); } logger.LogInformation("Reading clusters..."); List <float[][]> clusters = new List <float[][]>(); List <Template> templates = new List <Template>(); foreach (var file in Directory.GetFiles(args.ClustersDirectory)) { using (var stream = new StreamReader(file)) { var template = Template.Parse(file); var templateClusters = ServiceStack.Text.JsonSerializer.DeserializeFromReader <float[][]>(stream); templates.Add(template); clusters.Add(templateClusters); } } logger.LogInformation("Clusters are read succesfully"); var options = new ProgressBarOptions { ForegroundColor = ConsoleColor.Yellow, ForegroundColorDone = ConsoleColor.DarkGreen, BackgroundColor = ConsoleColor.DarkGray, BackgroundCharacter = '\u2593', DisplayTimeInRealTime = false }; // Temporary stub Span <float> tmp = series.Skip(series.Length - 1000).ToArray(); var totalTicks = tmp.Length - 80 - args.ForecastringSteps; IList <float> results; using (var pbar = new ProgressBar(totalTicks, "Progress of forecasting", options)) { void onPointForecasted() { pbar.Tick(); } SimpleForecaster.OnPointForecasted += onPointForecasted; results = SimpleForecaster.ForecastSeries(templates, clusters, tmp, args.Error, args.ForecastringSteps); SimpleForecaster.OnPointForecasted -= onPointForecasted; } var(rmse, nonpred) = MathExtended.CalculateRMSE(results, tmp.ToArray()); logger.LogInformation("RMSE = {rmse}", rmse); logger.LogInformation("Non predicted points = {nonpred}", nonpred); writer.Write(results, DefaultParams.forecastPath); //var next = SimpleForecaster.ForecastPoint(templates, clusters, tmp, args.Error, 10); //logger.LogInformation("Next point value = {next}", next); #if DEBUG Console.ReadKey(); #endif return(0); }
private void RegisterDefaultFunctions() { FunctionRegistry.RegisterFunction("sin", (Func <double, double>)Math.Sin, true, false); FunctionRegistry.RegisterFunction("cos", (Func <double, double>)Math.Cos, true, false); FunctionRegistry.RegisterFunction("csc", (Func <double, double>)MathUtil.Csc, true, false); FunctionRegistry.RegisterFunction("sec", (Func <double, double>)MathUtil.Sec, true, false); FunctionRegistry.RegisterFunction("asin", (Func <double, double>)Math.Asin, true, false); FunctionRegistry.RegisterFunction("acos", (Func <double, double>)Math.Acos, true, false); FunctionRegistry.RegisterFunction("tan", (Func <double, double>)Math.Tan, true, false); FunctionRegistry.RegisterFunction("cot", (Func <double, double>)MathUtil.Cot, true, false); FunctionRegistry.RegisterFunction("atan", (Func <double, double>)Math.Atan, true, false); FunctionRegistry.RegisterFunction("acot", (Func <double, double>)MathUtil.Acot, true, false); FunctionRegistry.RegisterFunction("loge", (Func <double, double>)Math.Log, true, false); FunctionRegistry.RegisterFunction("log10", (Func <double, double>)Math.Log10, true, false); FunctionRegistry.RegisterFunction("logn", (Func <double, double, double>)((a, b) => Math.Log(a, b)), true, false); FunctionRegistry.RegisterFunction("sqrt", (Func <double, double>)Math.Sqrt, true, false); FunctionRegistry.RegisterFunction("abs", (Func <double, double>)Math.Abs, true, false); FunctionRegistry.RegisterFunction("if", (Func <double, double, double, double>)((a, b, c) => (a != 0.0 ? b : c)), true, false); FunctionRegistry.RegisterFunction("ifless", (Func <double, double, double, double, double>)((a, b, c, d) => (a < b ? c : d)), true, false); FunctionRegistry.RegisterFunction("ifmore", (Func <double, double, double, double, double>)((a, b, c, d) => (a > b ? c : d)), true, false); FunctionRegistry.RegisterFunction("ifequal", (Func <double, double, double, double, double>)((a, b, c, d) => (a == b ? c : d)), true, false); FunctionRegistry.RegisterFunction("ceiling", (Func <double, double>)Math.Ceiling, true, false); FunctionRegistry.RegisterFunction("floor", (Func <double, double>)Math.Floor, true, false); FunctionRegistry.RegisterFunction("truncate", (Func <double, double>)Math.Truncate, true, false); FunctionRegistry.RegisterFunction("round", (Func <double, double>)Math.Round, true, false); // Dynamic based arguments Functions FunctionRegistry.RegisterFunction("max", (DynamicFunc <double, double>)((a) => a.Max()), true, false); FunctionRegistry.RegisterFunction("min", (DynamicFunc <double, double>)((a) => a.Min()), true, false); FunctionRegistry.RegisterFunction("avg", (DynamicFunc <double, double>)((a) => a.Average()), true, false); FunctionRegistry.RegisterFunction("median", (DynamicFunc <double, double>)((a) => MathExtended.Median(a)), true, false); // Non Idempotent Functions FunctionRegistry.RegisterFunction("random", (Func <double>)random.NextDouble, false, false); }
/* * Get keys function, the function get as a parameter key length window. it done because we need to read the length from this form * */ public void getKeys(KeyLengthWindow form) { // Generate two random numbers // Lets use our entropy based random generator Generator.Initialize(2); // For 1024 bit key length, we take 512 bits for first prime and 512 for second prime // Get same min and max BigInteger numMin = BigInteger.Pow(2, (form.BitLength / 2) - 1); BigInteger numMax = BigInteger.Pow(2, (form.BitLength / 2)); // Create two prime numbers var p = new PrimeNumber(); var q = new PrimeNumber(); p.SetNumber(Generator.Random(numMin, numMin)); q.SetNumber(Generator.Random(numMin, numMax)); // Create threaded p and q searches pThread = new Thread(p.RabinMiller); qThread = new Thread(q.RabinMiller); // For timeout DateTime start = DateTime.Now; pThread.Start(); qThread.Start(); while (pThread.IsAlive || qThread.IsAlive) { TimeSpan ts = DateTime.Now - start; if (ts.TotalMilliseconds > (1000 * 60 * 5)) { try { pThread.Abort(); } // ReSharper disable EmptyGeneralCatchClause catch (Exception) // ReSharper restore EmptyGeneralCatchClause { } try { qThread.Abort(); } // ReSharper disable EmptyGeneralCatchClause catch (Exception) // ReSharper restore EmptyGeneralCatchClause { } MessageBox.Show("Key generating error: timeout.\r\n\r\nIs your bit length too large?", "Error"); break; } } // If we found numbers, we continue to create if (p.GetFoundPrime() && q.GetFoundPrime()) { BigInteger n = p.GetPrimeNumber() * q.GetPrimeNumber(); BigInteger euler = (p.GetPrimeNumber() - 1) * (q.GetPrimeNumber() - 1); this.Dispatcher.Invoke((Action)(() => { messageStatusBar.Text = "Generating e prime number ..."; })); var primeNumber = new PrimeNumber(); while (true) { primeNumber.SetNumber(Generator.Random(2, euler - 1)); start = DateTime.Now; eThread = new Thread(primeNumber.RabinMiller); eThread.Start(); while (eThread.IsAlive) { TimeSpan ts = DateTime.Now - start; if (ts.TotalMilliseconds > (1000 * 60 * 5)) { MessageBox.Show("Key generating error: timeout.\r\n\r\nIs your bit length too large?", "Error"); break; } } if (primeNumber.GetFoundPrime() && (BigInteger.GreatestCommonDivisor(primeNumber.GetPrimeNumber(), euler) == 1)) { break; } } if (primeNumber.GetFoundPrime()) { this.Dispatcher.Invoke((Action)(() => { messageStatusBar.Text = "Calculating key components ..."; })); // Calculate secret exponent D as inverse number of E BigInteger d = MathExtended.ModularLinearEquationSolver(primeNumber.GetPrimeNumber(), 1, euler); //BigInteger d = MathExtended.ModularLinearEquationSolver(83, 1, 120); // Displaying keys if (d > 0) { // N (keysVM as KeysVM).PublicN = n.ToString(); (keysVM as KeysVM).PrivateN = n.ToString(); // E (keysVM as KeysVM).PublicE = primeNumber.GetPrimeNumber().ToString(); // D (keysVM as KeysVM).PrivateD = d.ToString(); this.Dispatcher.Invoke((Action)(() => { tabControl.SelectedIndex = 2; messageStatusBar.Text = "Successfully created key pair."; })); } else { this.Dispatcher.Invoke((Action)(() => { messageStatusBar.Text = "Error: Modular equation solver fault."; })); MessageBox.Show( "Error using mathematical extensions.\r\ne = " + primeNumber + "\r\neuler = " + euler + "\r\np = " + p.GetPrimeNumber() + "\r\n" + q.GetPrimeNumber(), "Error"); } } } else { this.Dispatcher.Invoke((Action)(() => { messageStatusBar.Text = "Idle"; })); } this.Dispatcher.Invoke((Action)(() => { this.progressBar.IsIndeterminate = false; })); }