Reputation: 274
I'm not familiar with all the collections available in C# but I'd like to implement a class to store a mathematical relation or function, i.e. a set of pairs (x,y). Presumably it would include a list of tuples or some other built collection from .NET, but I'm not sure what's best. Some potentially relevant facts:
Upvotes: 2
Views: 5209
Reputation: 79581
The SortedSet<T>
seems like the right tool for this task.
We can define an IComparable
element type as follows.
struct FunctionPoint : IComparable<FunctionPoint>
{
public double X, Y;
public FunctionPoint(double x)
{
this.X = x;
this.Y = 0;
}
public FunctionPoint(double x, double y)
{
this.X = x;
this.Y = y;
}
public int CompareTo(FunctionPoint other)
{
return X.CompareTo(other.X);
}
}
And then use it in a SortedSet<FunctionPoint>
as follows.
var function = new SortedSet<FunctionPoint>();
- up a million pairs
for (int i = 0; i < 100000; i++)
{
var x = 2 * Math.PI * i / 1000000;
var y = Math.Sin(x);
function.Add(new FunctionPoint { X = x, Y = y });
}
- frequently would want to lookup which y goes with a particular x
var view = function.GetViewBetween(new FunctionPoint(x), new FunctionPoint(x));
if (view.Count > 0)
{
var y = view.Min;
}
- may want to interpolate y's to nonexistant x's
var left = function.GetViewBetween(new FunctionPoint(double.NegativeInfinity), new FunctionPoint(x)).Max;
var right = function.GetViewBetween(new FunctionPoint(x), new FunctionPoint(double.PositiveInfinity)).Min;
var y = LinearInterpolate(left, right, x);
- will want to extract a subset of the relation including all pairs with x in a certain range
var view = function.GetViewBetween(new FunctionPoint(a), new FunctionPoint(b));
- will want to iterate through pairs in order of xs sometimes seems like it should be sorted by xs based on above things?
foreach (var point in function)
{
}
Upvotes: 4
Reputation: 8904
Maybe a System.Collections.Generic.SortedList<double, double>
is what you need?
SortedList
If you constantly remove and add items, a SortedDictionary might perform better.
Upvotes: 0