我還沒有聽說過任何的,但如果你所代表的約束間隔,你可以很容易地沒有他們:
X> 1000變爲(1000,double.Infinity)
X == 1000變爲[ 1000,1000]
等
這樣,你只需要一個類
class Constraint
{
double Lower; bool isLowerStrict;
double Upper; bool isUpperStrict;
bool isIn(double d)
{
return (isLowerStrict ? Lower < d : Lower <= d) &&
(isUpperStrict ? Upper > d : Upper >= d);
}
Constraint intersect(Constraint other)
{
Constraint result = new Constraint();
if (Lower > other.Lower)
{
result.Lower = Lower;
result.isLowerStrict = isLowerStrict;
}
else if (Lower < other.Lower)
{
result.Lower = other.Lower;
result.isLowerStrict = other.isLowerStrict;
}
else
{
result.Lower = Lower;
result.IsLowerStrict = isLowerStrict || other.isLowerStrict;
}
// the same for upper
return result;
}
public bool isEmpty()
{
if (Lower > Upper) return true;
if (Lower == Upper && (isLowerStrict || isUpperStrict)) return true;
return false;
}
public bool Equals(Constraint other)
{
if (isEmpty()) return other.isEmpty();
return (Lower == other.Lower) && (Upper = other.Upper) &&
(isLowerStrict == other.IsLowerStrict) &&
(isUpperStrict == other.isUpperStrict);
}
// construction:
static Constraint GreaterThan(double d)
{
return new Constraint()
{
Lower = d,
isLowerStrict = true,
Upper = double.PositiveInfinity,
isUpperStrict = false
};
}
static Constraint IsEqualTo(double d)
{
return new Constraint()
{
Lower = d,
isLowerStrict = false,
Upper = d,
isUpperStrict = false
};
}
// etc.
}
有了這個代碼,你可以回答的問題:
1)搭接:a.Intersect(b).isEmpty()
2)交叉:a.Intersect(b)
3)約束:a.Intersect(b).Equals(a)
編輯:
正如@CodeInChaos建議,你應該考慮用小數代替double。請注意,decimal不具有無限值,因此應該使用decimal.MaxValue和decimal.MinValue。
我首先搜索「解決線性不等式的系統」或類似的問題。 – Ani