AlmostEquals

Modified on 2013/05/11 09:45 by Eugene — Categorized as: Community Components

Syntax


public static bool AlmostEquals(this double double1, double double2, double precision)

public static bool AlmostEquals(double double1, double double2, double precision)

Parameter Description

double1First double value
double2Second double value
precisionDesirable precision when comparing

Description

Sometimes there's a need to compare two values of type double to determine whether they are within a close approximation to each other. The following function taken from Stackoverflow will handle it.

Example

Example below compares two double values for approximate equality within one tick value of an instrument.

Example using C# extension methods:


using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using WealthLab;
using WealthLab.Indicators;

namespace WealthLab.Strategies { public class AlmostEqualsDemo : WealthScript { protected override void Execute() { double tick = Bars.SymbolInfo.Tick; SetBarColors( Color.Silver, Color.Silver ); for(int bar = 1; bar < Bars.Count; bar++) { bool result = ( Close[bar].AlmostEquals(Low[bar],tick) || Close[bar].AlmostEquals(Low[bar]+tick,tick) || Open[bar].AlmostEquals(Low[bar],tick) || Open[bar].AlmostEquals(Low[bar]+tick,tick) ); if( result ) SetBarColor( bar, Color.Magenta ); } } } }

Legacy syntax example:


using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using WealthLab;
using WealthLab.Indicators;
using Community.Components;

namespace WealthLab.Strategies { using c = Community.Components.Calculate; public class AlmostEqualsDemo : WealthScript { protected override void Execute() { double tick = Bars.SymbolInfo.Tick; SetBarColors( Color.Silver, Color.Silver ); for(int bar = 1; bar < Bars.Count; bar++) { bool result = ( c.AlmostEquals(Close[bar],Low[bar],tick) || c.AlmostEquals(Close[bar],Low[bar]+tick,tick) || c.AlmostEquals(Open[bar],Low[bar],tick) || c.AlmostEquals(Open[bar],Low[bar]+tick,tick) ); if( result ) SetBarColor( bar, Color.Magenta ); } } } }