public void Normalization(Boolean colbycol) { // 현재는 Standardize 만을 지원한다. if (colbycol == true) { for (Int32 i = 0; i < dimension; i++) { Double[] target = new Double[count]; for (Int32 j = 0; j < count; j++) { target[j] = vectors[j].Data[i]; } Double mean = target.Average(); Double stdev = target.PopulationStandardDeviation(); for (Int32 j = 0; j < count; j++) { vectors_norm[j].Data[i] = (target[j] - mean) / stdev; } } } else { for (Int32 i = 0; i < count; i++) { Double mean = vectors[i].Data.Average(); Double stdev = vectors[i].Data.PopulationStandardDeviation(); for (Int32 j = 0; j < dimension; j++) { vectors_norm[i].Data[j] = (vectors[i].Data[j] - mean) / stdev; } } } isNormalized = true; }
public double CalculateDifference(int[] cameras) { var compareResults = new Double[cameras.Length]; try { for (var i = 0; i < cameras.Length; i++) { var fswebcamCommand = $"fswebcam -d /dev/video{cameras[i]} {FsWebCamParams} {DiffImage(cameras[i])}"; var processTakeImage = _bashRunner.RunCommand( fswebcamCommand, Environment.CurrentDirectory, true, null, FsWebCamRetrys); if (processTakeImage.ExitCode != 0) { throw new ExceptionNoFsWebCam($"Could not take diff images with fswebcam. Command: {fswebcamCommand}"); } var compareCommand = $"compare -fuzz 5% -metric AE {BaselineImage(cameras[i])} {DiffImage(cameras[i])} diffresult{cameras[i]}.jpg"; var processDiff = _bashRunner.RunCommand( compareCommand, Environment.CurrentDirectory, true, null, null); //HACK: This call comes out as an error, but actually its ok compareResults[i] = Convert.ToDouble(processDiff.StandardError.ReadToEnd()); } } catch (AggregateException ae) { throw ae.InnerException; } return(compareResults.Average()); }
static void Main(string[] args) { double[] nums = new Double[30]; //Definiciones e inicializaciones de variables Random randomizer = new Random(); for (int i = 0; i <= 29; i++) { nums[i] = randomizer.NextDouble() * 100; // Se le asigna al vector los numeros al azar } //Muestra en pantalla el resultado Console.WriteLine("Máximo: " + nums.Max()); Console.WriteLine("Mínimo: " + nums.Min()); Console.WriteLine("Promedio: " + nums.Average()); Console.ReadKey(); }
public void FillDoubleArray_ShouldProduceDesiredResults_ForBoundedInvocation() { // Arrange. var arrayLength = 180; var floor = -100000d; var ceiling = 100000d; var array = new Double[arrayLength]; using (var randomNumberGenerator = RandomNumberGenerator.Create()) { // Act. randomNumberGenerator.FillDoubleArray(array, floor, ceiling); // Assert. array.Length.Should().Be(arrayLength); array.Average().Should().BeGreaterOrEqualTo(-50000d).And.BeLessOrEqualTo(50000d); } }
// This function has the logic which calculates standard Error for the option with Delta Control Variate public void calculateStandardErrorwithcv(long numberOfSimulations, Double[] priceAtEnd, Double daysToExpiry, Boolean antitheticReduction, Double[] controlVariateList) { Double sum2 = 0; numberOfSimulations = antitheticReduction ? 2 * numberOfSimulations : numberOfSimulations; Double num = 0, den = 0; Double[] payoff = new Double[priceAtEnd.Length]; for (int i = 0; i < priceAtEnd.Length; i++) { if (this.type == OptionType.CALL) { payoff[i] = Math.Max(priceAtEnd[i] - this.strikePrice, 0); } else { payoff[i] = Math.Max(this.strikePrice - priceAtEnd[i], 0); } } Double pa = payoff.Average(), cva = controlVariateList.Average(); for (int i = 0; i < priceAtEnd.Length; i++) { num += (payoff[i] - pa) * (controlVariateList[i] - cva); den += Math.Pow((payoff[i] - pa), 2); } Double beta = num / den; for (int i = 0; i < priceAtEnd.Length; i++) { if (this.type == OptionType.CALL) { sum2 += Math.Pow(Math.Max(priceAtEnd[i] - this.strikePrice, 0) - beta * controlVariateList[i], 2); } else if (this.type == OptionType.PUT) { sum2 += Math.Pow(Math.Max(this.strikePrice - priceAtEnd[i], 0) - beta * controlVariateList[i], 2); } } this.StandarError = Math.Sqrt(((sum2 - Math.Pow(this.price, 2)) * Math.Exp(-2 * Simulator.yieldCurve[0].Rate * (daysToExpiry / 365.0))) / (numberOfSimulations - 1)) / Math.Sqrt(numberOfSimulations); }
private static void Run(Compute c, int n, int threads, bool inops, bool precision64Bit) { const int repeats = 3; Double[] times = new Double[repeats]; Double[] gxops = new Double[repeats]; Console.WriteLine("\n{0}{1} tests in {2} {3}, N: {4}", inops ? "INT" : "FLT", precision64Bit ? "64" : "32", threads, "thread(s)", n); Console.Write(inops ? "G_INOPS: " : "G_FLOPS: "); for (int i = 0; i < repeats; i++) { if (inops && threads == 1) { times[i] = c.RunXops(n, inops, precision64Bit); gxops[i] = c.LastResultSTGigaOPSAveraged; //gxops[i] = (double)Compute.inopsPerIteration * n / times[i] / 1000000000; } else if (inops && threads > 1) { times[i] = c.RunXopsMultiThreaded(n, threads, inops: true, precision64Bit: precision64Bit); gxops[i] = (double)Compute.inopsPerIteration * n * threads / times[i] / 1000000000; } else if (!inops && threads == 1) { times[i] = c.RunXops(n, inops, precision64Bit); gxops[i] = c.LastResultSTGigaOPSAveraged; //gxops[i] = (double)Compute.flopsPerIteration * n / times[i] / 1000000000; } else if (!inops && threads > 1) { times[i] = c.RunXopsMultiThreaded(n, threads, inops: false, precision64Bit: precision64Bit); gxops[i] = (double)Compute.flopsPerIteration * n * threads / times[i] / 1000000000; } Console.Write("{0:0.00}; ", gxops[i]); } Console.WriteLine("\n{1:0.00} {0}, {2:0.00}ms - averages", inops ? "G_INOPS" : "G_FLOPS", gxops.Average(), times.Average() * 1000); }
private async void GetWeather() { ColorSnow.Color = Color.FromArgb(255, 255, 255, 255); ColorRain.Color = Color.FromArgb(255, 16, 155, 251); Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.f") + " - Request Weather Data..."); WebRequest W_wrGETURL = WebRequest.Create("http://api.wunderground.com/api/877361112ea5ac9f/geolookup/conditions/hourly/q/Switzerland/Winterthur.json"); WebResponse W_response = await W_wrGETURL.GetResponseAsync(); Stream W_dataStream = W_response.GetResponseStream(); StreamReader W_reader = new StreamReader(W_dataStream); string W_sResponse = W_reader.ReadToEnd(); Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.f") + " - ...Data received"); Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.f") + " - Loading Weather Data Stream"); WeatherRootObject WeatherObj = JsonConvert.DeserializeObject <WeatherRootObject>(W_sResponse); Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.f") + " - Parsing Weather Data Stream"); Double[] temp_raw = new Double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; Double[] rain_raw = new Double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; Double vAvg, vScale; Label_Time1.Text = WeatherObj.hourly_forecast[3].FCTTIME.hour_padded + ":00"; Label_Time2.Text = WeatherObj.hourly_forecast[6].FCTTIME.hour_padded + ":00"; Label_Time3.Text = WeatherObj.hourly_forecast[9].FCTTIME.hour_padded + ":00"; Label_Time4.Text = WeatherObj.hourly_forecast[12].FCTTIME.hour_padded + ":00"; Label_Time5.Text = WeatherObj.hourly_forecast[15].FCTTIME.hour_padded + ":00"; Label_Time6.Text = WeatherObj.hourly_forecast[18].FCTTIME.hour_padded + ":00"; Label_Temp1.Text = String.Format("{0:N0}°C", WeatherObj.hourly_forecast[3].temp.metric); Label_Temp2.Text = String.Format("{0:N0}°C", WeatherObj.hourly_forecast[6].temp.metric); Label_Temp3.Text = String.Format("{0:N0}°C", WeatherObj.hourly_forecast[9].temp.metric); Label_Temp4.Text = String.Format("{0:N0}°C", WeatherObj.hourly_forecast[12].temp.metric); Label_Temp5.Text = String.Format("{0:N0}°C", WeatherObj.hourly_forecast[15].temp.metric); Label_Temp6.Text = String.Format("{0:N0}°C", WeatherObj.hourly_forecast[18].temp.metric); image1.Source = new BitmapImage(new Uri("ms-appx:///Assets/Weather/" + WeatherObj.hourly_forecast[3].fctcode + ".png")); image2.Source = new BitmapImage(new Uri("ms-appx:///Assets/Weather/" + WeatherObj.hourly_forecast[6].fctcode + ".png")); image3.Source = new BitmapImage(new Uri("ms-appx:///Assets/Weather/" + WeatherObj.hourly_forecast[9].fctcode + ".png")); image4.Source = new BitmapImage(new Uri("ms-appx:///Assets/Weather/" + WeatherObj.hourly_forecast[12].fctcode + ".png")); image5.Source = new BitmapImage(new Uri("ms-appx:///Assets/Weather/" + WeatherObj.hourly_forecast[15].fctcode + ".png")); image6.Source = new BitmapImage(new Uri("ms-appx:///Assets/Weather/" + WeatherObj.hourly_forecast[18].fctcode + ".png")); for (byte i = 0; i <= 21; i++) { temp_raw[i] = Convert.ToInt32(WeatherObj.hourly_forecast[i].temp.metric); } vAvg = temp_raw.Average(); vScale = 20 / (Math.Abs(temp_raw.Max()) - Math.Abs(temp_raw.Min())); for (byte i = 0; i <= 21; i++) { double x_old = TempLine.Points.ElementAt(i + 1).X; y_temp_set[i] = 120 - Convert.ToInt32(Convert.ToInt32(WeatherObj.hourly_forecast[i].temp.metric) * vScale); TempLine.Points.RemoveAt(i + 1); TempLine.Points.Insert(i + 1, AsPoint(Convert.ToInt32(x_old), y_temp_set[i])); } Label_Temp1.SetValue(Canvas.TopProperty, (y_temp_set[3] - 25)); image1.SetValue(Canvas.TopProperty, (y_temp_set[3] - 70)); Label_Temp2.SetValue(Canvas.TopProperty, (y_temp_set[6] - 25)); image2.SetValue(Canvas.TopProperty, (y_temp_set[6] - 70)); Label_Temp3.SetValue(Canvas.TopProperty, (y_temp_set[9] - 25)); image3.SetValue(Canvas.TopProperty, (y_temp_set[9] - 70)); Label_Temp4.SetValue(Canvas.TopProperty, (y_temp_set[12] - 25)); image4.SetValue(Canvas.TopProperty, (y_temp_set[12] - 70)); Label_Temp5.SetValue(Canvas.TopProperty, (y_temp_set[15] - 25)); image5.SetValue(Canvas.TopProperty, (y_temp_set[15] - 70)); Label_Temp6.SetValue(Canvas.TopProperty, (y_temp_set[18] - 25)); image6.SetValue(Canvas.TopProperty, (y_temp_set[18] - 70)); Rect_Rain11.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[0].pop)); Rect_Rain11.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[0].pop)); Rect_Rain12.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[1].pop)); Rect_Rain12.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[1].pop)); Rect_Rain13.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[2].pop)); Rect_Rain13.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[2].pop)); Rect_Rain21.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[3].pop)); Rect_Rain21.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[3].pop)); Rect_Rain22.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[4].pop)); Rect_Rain22.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[4].pop)); Rect_Rain23.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[5].pop)); Rect_Rain23.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[5].pop)); Rect_Rain31.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[6].pop)); Rect_Rain31.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[6].pop)); Rect_Rain32.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[7].pop)); Rect_Rain32.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[7].pop)); Rect_Rain33.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[8].pop)); Rect_Rain33.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[8].pop)); Rect_Rain41.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[9].pop)); Rect_Rain41.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[9].pop)); Rect_Rain42.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[10].pop)); Rect_Rain42.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[10].pop)); Rect_Rain43.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[11].pop)); Rect_Rain43.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[11].pop)); Rect_Rain51.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[12].pop)); Rect_Rain51.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[12].pop)); Rect_Rain52.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[13].pop)); Rect_Rain52.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[13].pop)); Rect_Rain53.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[14].pop)); Rect_Rain53.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[14].pop)); Rect_Rain61.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[15].pop)); Rect_Rain61.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[15].pop)); Rect_Rain62.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[16].pop)); Rect_Rain62.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[16].pop)); Rect_Rain63.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[17].pop)); Rect_Rain63.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[17].pop)); // Current Weather image_cur.Source = new BitmapImage(new Uri("ms-appx:///Assets/Weather/big/" + WeatherObj.current_observation.icon + ".png")); Label_CurTemp.Text = WeatherObj.current_observation.temp_c + "°C"; Label_CurFeel.Text = "Feels like " + WeatherObj.current_observation.feelslike_c + "°C"; Label_CurPerc.Text = "The weather is " + WeatherObj.current_observation.weather.ToLower() + " with a forecasted percipitation of " + WeatherObj.current_observation.precip_today_metric + "mm. " + "The wind blows from " + WeatherObj.current_observation.wind_dir.ToLower() + " direction with " + WeatherObj.current_observation.wind_kph + "kmh."; Int32[] rain_forecast = new Int32[] { Convert.ToInt32(WeatherObj.hourly_forecast[0].pop), Convert.ToInt32(WeatherObj.hourly_forecast[1].pop), Convert.ToInt32(WeatherObj.hourly_forecast[2].pop), Convert.ToInt32(WeatherObj.hourly_forecast[3].pop), Convert.ToInt32(WeatherObj.hourly_forecast[4].pop), Convert.ToInt32(WeatherObj.hourly_forecast[5].pop), Convert.ToInt32(WeatherObj.hourly_forecast[6].pop), Convert.ToInt32(WeatherObj.hourly_forecast[7].pop), Convert.ToInt32(WeatherObj.hourly_forecast[8].pop), Convert.ToInt32(WeatherObj.hourly_forecast[9].pop), Convert.ToInt32(WeatherObj.hourly_forecast[10].pop), Convert.ToInt32(WeatherObj.hourly_forecast[11].pop) }; Int32[] wind_forecast = new Int32[] { Convert.ToInt32(WeatherObj.hourly_forecast[0].wspd.metric), Convert.ToInt32(WeatherObj.hourly_forecast[1].wspd.metric), Convert.ToInt32(WeatherObj.hourly_forecast[2].wspd.metric), Convert.ToInt32(WeatherObj.hourly_forecast[3].wspd.metric), Convert.ToInt32(WeatherObj.hourly_forecast[4].wspd.metric), Convert.ToInt32(WeatherObj.hourly_forecast[5].wspd.metric), Convert.ToInt32(WeatherObj.hourly_forecast[6].wspd.metric), Convert.ToInt32(WeatherObj.hourly_forecast[7].wspd.metric), Convert.ToInt32(WeatherObj.hourly_forecast[8].wspd.metric), Convert.ToInt32(WeatherObj.hourly_forecast[9].wspd.metric), Convert.ToInt32(WeatherObj.hourly_forecast[10].wspd.metric), Convert.ToInt32(WeatherObj.hourly_forecast[11].wspd.metric) }; if (DateTime.Now.Hour < 12) { s1 = "Good morning! "; } else { s1 = "Hi there! "; } if (rain_forecast.Max() > 20) { s2 = "Stay dry, it might rain"; if (wind_forecast.Average() > 10) { s3 = " and look out for flying cows, it's windy!"; } else { s3 = "."; } } else { s2 = "A dry day is forcasted, enjoy"; if (wind_forecast.Average() > 10) { s3 = ". But look out for flying cows, it's windy!"; } else { s3 = "."; } } Label_CurPerc.Text = s1 + s2 + s3; }
//This function creates an path of the stock which we assume for brownian geometric motion. #region Create Path for Underlying public static Double[] getPath(Options option, long noOfSimulations, int numberOfDays, Double del, ChangeValue change, bool controlVariateReduction, bool multithreading = true, GraphPlotting plot = null) { changeValues(option, del, change); Double[] priceAtEnd = new Double[noOfSimulations]; int numberofThreads = multithreading ? Environment.ProcessorCount : 1; Double dt = Convert.ToDouble((option.ExpiryDate - DateTime.Today).Days) / (365 * numberOfDays); if (controlVariateReduction) { controlVariateList.Clear(); } int day = 0; Parallel.ForEach(randomNumbers, new ParallelOptions { MaxDegreeOfParallelism = numberofThreads }, randomList => { Double[] simulatedPathForOneSimulation = new Double[numberOfDays + 1]; simulatedPathForOneSimulation[0] = option.Underlying.Price; double controlVariate = 0; for (int time = 1; time <= numberOfDays; time++) { try { simulatedPathForOneSimulation[time] = simulatedPathForOneSimulation[time - 1] * Math.Exp(((yieldCurve[0].Rate - (Math.Pow(option.HistoricalVolatility, 2) / 2.0)) * (dt)) + option.HistoricalVolatility * Math.Sqrt(dt) * randomList[time - 1]); if (controlVariateReduction) { Double delta = OptionDelta(simulatedPathForOneSimulation[time - 1], option.StrikePrice, yieldCurve[0].Rate, option.HistoricalVolatility, (numberOfDays - time) * dt); if (option.Type == OptionType.PUT) { delta = delta - 1; } controlVariate += delta * (simulatedPathForOneSimulation[time] - (simulatedPathForOneSimulation[time - 1] * Math.Exp(yieldCurve[0].Rate * dt))); } } catch (Exception e) { throw e; } } lock (lck) { if (plot != null && day <= 0) { plot.addNewSeries(simulatedPathForOneSimulation); } switch (option.OptionKind) { case OptionKind.ASIAN: priceAtEnd[day++] = simulatedPathForOneSimulation.Average(); break; case OptionKind.BARRIER: switch (((BarrierOption)option).BarrierOptionType) { case BarrierOptionType.UPOUT: if (simulatedPathForOneSimulation.Max() > ((BarrierOption)option).Barrier) { priceAtEnd[day++] = -1; } else { priceAtEnd[day++] = simulatedPathForOneSimulation[simulatedPathForOneSimulation.Length - 1]; } break; case BarrierOptionType.UPIN: if (simulatedPathForOneSimulation.Max() <= ((BarrierOption)option).Barrier) { priceAtEnd[day++] = -1; } else { priceAtEnd[day++] = simulatedPathForOneSimulation[simulatedPathForOneSimulation.Length - 1]; } break; case BarrierOptionType.DOWNOUT: if (simulatedPathForOneSimulation.Min() < ((BarrierOption)option).Barrier) { priceAtEnd[day++] = -1; } else { priceAtEnd[day++] = simulatedPathForOneSimulation[simulatedPathForOneSimulation.Length - 1]; } break; case BarrierOptionType.DOWNIN: if (simulatedPathForOneSimulation.Min() >= ((BarrierOption)option).Barrier) { priceAtEnd[day++] = -1; } else { priceAtEnd[day++] = simulatedPathForOneSimulation[simulatedPathForOneSimulation.Length - 1]; } break; default: break; } break; case OptionKind.DIGITAL: priceAtEnd[day++] = simulatedPathForOneSimulation[simulatedPathForOneSimulation.Length - 1]; break; case OptionKind.EUROPEAN: priceAtEnd[day++] = simulatedPathForOneSimulation[simulatedPathForOneSimulation.Length - 1]; break; case OptionKind.LOOKBACK: switch (option.Type) { case OptionType.CALL: priceAtEnd[day++] = simulatedPathForOneSimulation.Max(); break; case OptionType.PUT: priceAtEnd[day++] = simulatedPathForOneSimulation.Min(); break; default: break; } break; case OptionKind.RANGE: priceAtEnd[day++] = simulatedPathForOneSimulation.Max() - simulatedPathForOneSimulation.Min(); break; default: priceAtEnd[day++] = simulatedPathForOneSimulation[simulatedPathForOneSimulation.Length - 1]; break; } if (controlVariateReduction) { controlVariateList.Add(controlVariate); } } }); if (change != ChangeValue.RATE && change != ChangeValue.TIME) { changeValues(option, -1 * del, change); } return(priceAtEnd); }
public void updateData() { if (initialized) { Int64 pos = 0; state = shmem.ReadInt32(pos); pos += sizeof(Int32); carid = shmem.ReadInt32(pos); pos += sizeof(Int32); gear = shmem.ReadInt32(pos); pos += sizeof(Int32); lap = shmem.ReadInt32(pos); pos += sizeof(Int32); totallaps = shmem.ReadInt32(pos); pos += sizeof(Int32); position = shmem.ReadInt32(pos); pos += sizeof(Int32); pitlimiter = shmem.ReadInt32(pos); pos += sizeof(Int32); sessiontype = shmem.ReadInt32(pos); pos += sizeof(Int32); carinfront = shmem.ReadInt32(pos); pos += sizeof(Int32); timestamp = shmem.ReadDouble(pos); pos += sizeof(Double); speed = shmem.ReadDouble(pos); pos += sizeof(Double); rpm = shmem.ReadDouble(pos); pos += sizeof(Double); fuel = shmem.ReadDouble(pos); pos += sizeof(Double); prevlap = shmem.ReadDouble(pos); pos += sizeof(Double); trackLength = shmem.ReadDouble(pos); pos += sizeof(Double); maxrpm = shmem.ReadDouble(pos); pos += sizeof(Double); shmem.ReadArray <Double>(pos, driverTrkPos, 0, maxcars); pos += maxcars * sizeof(Double); Byte[] buf = new Byte[64]; shmem.ReadArray <Byte>(pos, buf, 0, 64); pos += 64 * sizeof(Byte); buf = Encoding.Convert(Encoding.GetEncoding("iso-8859-1"), Encoding.UTF8, buf); carname = Encoding.UTF8.GetString(buf, 0, 64); carname = carname.Substring(0, carname.IndexOf('\0')); shmem.ReadArray <Byte>(pos, buf, 0, 64); pos += 64 * sizeof(Byte); buf = Encoding.Convert(Encoding.GetEncoding("iso-8859-1"), Encoding.UTF8, buf); trackname = Encoding.UTF8.GetString(buf, 0, 64); trackname = trackname.Substring(0, trackname.IndexOf('\0')); // process if (needReset && trackLength > 0) { reset(); LoadBestLap(); needReset = false; } if (prevstate != state) { if (state == 2) // entering driving mode { LoadBestLap(); } else if (prevstate == 2) // exiting driving mode { SaveBestLap(); } prevstate = state; } timedelta.Update(timestamp, driverTrkPos); if (driverTrkPos[carid] < 0.1 && lastTickTrackPos > 0.9) { Double distance = (1 - lastTickTrackPos) + driverTrkPos[carid]; Double time = timestamp - lastTickTime; Double tickCorrection = (1 - lastTickTrackPos) / distance; // save lap time if (lapTimeValid) { fuelcons[fuelconsPtr % fuelcons.Length] = fuel; // update fuel consumption after one full lap if (fuelconsPtr > 0) { if (fuelconsPtr >= fuelcons.Length) { Double[] consrate = new Double[fuelcons.Length - 1]; Int32 j = 0; for (int i = fuelconsPtr; i < fuelconsPtr + consrate.Length; i++) { consrate[j++] = fuelcons[(i + 1) % fuelcons.Length] - fuelcons[(i + 2) % fuelcons.Length]; } fuelneed = (Int32)(fuelcons[fuelconsPtr % fuelcons.Length] - ((totallaps - lap) * consrate.Average())); fuelconsumption = consrate.Average(); } else if (fuelconsPtr > 0) { fuelneed = (Int32)(fuelcons[fuelconsPtr % fuelcons.Length] - ((totallaps - lap) * fuelcons[(fuelconsPtr - 1) % fuelcons.Length])); fuelconsumption = fuelcons[(fuelconsPtr - 1) % fuelcons.Length] - fuelcons[fuelconsPtr % fuelcons.Length]; } } fuelconsPtr++; } // start new lap lapStartTime = timestamp - (1 - tickCorrection) * time; lapTimeValid = true; // reset fuel consumption when in pits if (driverTrkPos[carid] < 0) { fuelcons = new Double[fuelconslaps]; fuelconsPtr = 0; } } else if (Math.Abs(driverTrkPos[carid] - lastTickTrackPos) > 0.1) { // invalidate lap time if jumping too much lapTimeValid = false; } lastTickTrackPos = driverTrkPos[carid]; // save for next tick lastTickTime = timestamp; if (sessiontype >= 10) // if (race) { delta = timedelta.GetDelta(carid, carinfront); } else { delta = timedelta.GetBestLapDelta(driverTrkPos[carid] % 1); } } }
private void Run(Compute c, int n, int threads, bool inops, bool useTasks) { const int repeats = 4; Double[] times = new Double[repeats]; Double[] gxops = new Double[repeats]; WriteLine(string.Format("\n{0} tests in {1} {2}, N: {3}", inops ? "INT32" : "FLT32", threads, useTasks ? "tasks" : "threads", n)); Write(string.Format(inops ? "G_INOPS: " : "G_FLOPS: ")); for (int i = 0; i < repeats; i++) { if (inops && threads == 1) { times[i] = c.RunInops32Bit(n); gxops[i] = (double)Compute.inopsPerIteration * n / times[i] / 1000000000; } else if (inops && threads > 1) { times[i] = c.RunXopsMultiThreaded(n, threads, inops: true, useTasks: useTasks); gxops[i] = (double)Compute.inopsPerIteration * n * threads / times[i] / 1000000000; } else if (!inops && threads == 1) { times[i] = c.RunFlops64Bit(n); gxops[i] = (double)Compute.flopsPerIteration * n / times[i] / 1000000000; } else if (!inops && threads > 1) { times[i] = c.RunXopsMultiThreaded(n, threads, inops: false, useTasks: useTasks); gxops[i] = (double)Compute.flopsPerIteration * n * threads / times[i] / 1000000000; } Write(string.Format("{0:0.00}; ", gxops[i])); } WriteLine(string.Format("\nAverage {0}: {1}", inops ? "G_INOPS" : "G_FLOPS", gxops.Average())); }