Browse Source

TolerantMath: implemented Floor and Ceiling

af/merge-core
Anton Firszov 8 years ago
parent
commit
a5c5f618b3
  1. 28
      src/ImageSharp/Common/Helpers/TolerantMath.cs
  2. 38
      tests/ImageSharp.Tests/Helpers/TolerantMathTests.cs
  3. 3
      tests/ImageSharp.Tests/ImageSharp.Tests.csproj

28
src/ImageSharp/Common/Helpers/TolerantMath.cs

@ -1,12 +1,14 @@
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Runtime.CompilerServices;
namespace SixLabors.ImageSharp
{
/// <summary>
/// Implements math operations using tolerant comparison.
/// Implements basic math operations using tolerant comparison
/// whenever an equality check is needed.
/// </summary>
internal struct TolerantMath
{
@ -71,5 +73,29 @@ namespace SixLabors.ImageSharp
/// </summary>
[MethodImpl(InliningOptions.ShortMethod)]
public bool IsLessOrEqual(double a, double b) => b >= a - this.epsilon;
[MethodImpl(InliningOptions.ShortMethod)]
public double Ceiling(double a)
{
double rem = Math.IEEERemainder(a, 1);
if (this.IsZero(rem))
{
return Math.Round(a);
}
return Math.Ceiling(a);
}
[MethodImpl(InliningOptions.ShortMethod)]
public double Floor(double a)
{
double rem = Math.IEEERemainder(a, 1);
if (this.IsZero(rem))
{
return Math.Round(a);
}
return Math.Floor(a);
}
}
}

38
tests/ImageSharp.Tests/Helpers/TolerantMathTests.cs

@ -126,5 +126,43 @@ namespace SixLabors.ImageSharp.Tests.Helpers
Assert.False(this.tolerantMath.IsGreaterOrEqual(a, b));
Assert.False(this.tolerantMath.IsLessOrEqual(b, a));
}
[Theory]
[InlineData(3.5, 4.0)]
[InlineData(3.89, 4.0)]
[InlineData(4.09, 4.0)]
[InlineData(4.11, 5.0)]
[InlineData(0.11, 1)]
[InlineData(0.05, 0)]
[InlineData(-0.5, 0)]
[InlineData(-0.95, -1)]
[InlineData(-1.05, -1)]
[InlineData(-1.5, -1)]
public void Ceiling(double value, double expected)
{
double actual = this.tolerantMath.Ceiling(value);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(1, 1)]
[InlineData(0.99, 1)]
[InlineData(0.5, 0)]
[InlineData(0.01, 0)]
[InlineData(-0.09, 0)]
[InlineData(-0.11, -1)]
[InlineData(-100.11, -101)]
[InlineData(-100.09, -100)]
public void Floor(double value, double expected)
{
double plz1 = Math.IEEERemainder(1.1, 1);
double plz2 = Math.IEEERemainder(0.9, 1);
double plz3 = Math.IEEERemainder(-1.1, 1);
double plz4 = Math.IEEERemainder(-0.9, 1);
double actual = this.tolerantMath.Floor(value);
Assert.Equal(expected, actual);
}
}
}

3
tests/ImageSharp.Tests/ImageSharp.Tests.csproj

@ -1,6 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net462;net472;netcoreapp2.1</TargetFrameworks>
<!--<TargetFrameworks>net462;net472;netcoreapp2.1</TargetFrameworks>-->
<TargetFramework>netcoreapp2.1</TargetFramework>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<LangVersion>latest</LangVersion>
<DebugType Condition="$(codecov) != ''">full</DebugType>

Loading…
Cancel
Save