Code Monkey home page Code Monkey logo

fixpointcs's Introduction

FixPointCS

A fast, multi-language, multi-precision fixed-point library!


Key Features

  • Deterministic: Operations produce bit-identical results across languages and compilers
  • Fast: All operations use efficient algorithms and are highly optimized
  • Multi-Language: Supports C#, Java, and C++
  • Multiple Types: Supports signed 32.32 and 16.16 fixed-point numbers
  • Multiple Precisions: Operations provide variants with 24, 16, and 10 bits of precision
  • Extensive: All standard math functions supported, except hyperbolic trigonometry
  • Well Tested: The library comes with a comprehensive performance and precision testing suite

Overview

FixPointCS aims to provide as robust and efficient core math operations as possible, while keeping the API simple to stay compatible with multiple languages. It is intended to be a building block for higher-level math libraries, not to be used directly from application code.

For convenience, FixPointCS does include a higher-level math library as well (only for C#). It is provided as an example on how to utilize the core primitives. It also be used as-is, or customized to a project's needs. The convenience library is located in Examples/FixMath.

Getting Started

Core Math Library (all languages)

The simplest and recommended way to use FixPointCS is to copy the relevant source files directly into your project. The core math operations reside in the following files:

  • For C#: FixPointCS/Fixed32.cs, FixPointCS/Fixed64.cs and FixPointCS/FixedUtil.cs
  • For Java: Java/Fixed32.java, Java/Fixed64.java and Java/FixedUtil.java
  • For C++: Cpp/Fixed64.h, Cpp/Fixed32.h and Cpp/FixedUtil.h

FixMath Convenience Library (C# only)

For C#, you can also use the provided higher-level math library, located under Examples/FixMath. In order to get started writing applications as easily as possible, using the example library is recommended.

The FixMath library provides basic scalar types (F32 and F64, signed 16.16 and 32.32 fixed-point values, respectively), as well as vector types (F32VecN and F64VecN).

For examples on how to use the FixMath library, see Examples/FixedTracer/FixedTracer.cs, which implements a simple fixed-point raytracer.

Supported Functions

Supported operations include:

  • Arithmetic: Add(), Sub(), Mul(), Div(), Rcp() (reciprocal), Mod() (modulo)
  • Trigonometry: Sin(), Cos(), Tan(), Asin(), Acos(), Atan(), Atan2()
  • Exponential: Exp(), Exp2(), Log(), Log2(), Pow()
  • Square root: Sqrt(), RSqrt() (reciprocal square root)
  • Utility: Abs(), Nabs(), Sign(), Ceil(), Floor(), Round(), Fract(), Min(), Max(), Clamp(), Lerp()
  • Conversions: CeilToInt(), FloorToInt(), RoundToInt(), FromDouble(), FromFloat(), ToDouble(), ToFloat()

Note that the conversions to/from floating point values are not guaranteed to be deterministic.

For full list of supported operations, see functions.md.

Precision Guide

The library supports both signed 32.32 fixed-point type (Fixed64), and signed 16.16 fixed-point (Fixed32). For each operation, for both types, each approximate function comes with three precision variants with different speed/precision trade off. For example, Sin() has 24 bits of precision, SinFast() has 16 bits of precision and SinFastest() has 10 bits of precision.

The precision is relative to the output value, so for example 10 bits of precision means that the answer is accurate to about 1 part in 1000 (or has error margin of 0.1%). The Fast variant is typically about 10-15% faster than the highest precision, and the Fastest variant about 20-30% faster. See functions.md for details.

Div and Sqrt also come with a Precise variant (DivPrecise(), SqrtPrecise()), which produce a result that is exactly correct within representable fixed-point numbers.

Known Limitations

  • Few operations are much slower without a 64-bit CPU, most notably s32.32 multiply and division
  • The library opts for performance and determinism over full correctness in edge cases like overflows

License

Available under MIT license, see LICENSE.txt for details.

fixpointcs's People

Contributors

petrikero avatar xmunkki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fixpointcs's Issues

Is this library ready for production code? What about FixedMath.Net?

Hello ๐Ÿ‘‹, thank you for your support.

I noticed that this libraries version is 0.3, does that mean that is not fully developed yet? Is this library ready for business production code, without it having to be altered by us?

Also there is another library that is accessible through the nuget package manager: https://www.nuget.org/packages/FixedMath.NET/. Its github link: https://github.com/asik/FixedMath.Net. Do you guys know this library, if so, what can you tell me about it, should it be used for production code instead? Is there a problem with this library, and that is why you are creation yours?

constexpr support for C++?

Would it be a bad idea to define C++ methods as constexpr?

This would facilitate defining non trivial constexpr values in applications.

I'd appreciate any thoughts.

Thank you!

about precision error

I calcd a value of F64Vec3, i use c#ใ€‚
i known result is (0.0, 0.0, 1.4)
but F64Vec3 result is (-1.93249434232712E-08, 0, 1.39999999897555)
i write a function convert F64Vec3 result to Unity's Vector3
public Vector3 ToUnityVector3()
{
return new Vector3(X.Float, Y.Float, Z.Float);
}
that is return (0.0, 0.0, 1.4). X is F64Vec3.X, Y is F64Vec3.Y, Z is F64Vec3.Z
i want to use (0.0, 0.0, 1.4), but do not want use ToUnityVector3.
what shall i do ?

Throw Exceptions for invalid input

Currently, providing an invalid input to functions like Sqrt(<0) simply returns 0, which hides the problem and leads to debugging hell.

Returning a corrent result (NaN, #6 ) instead of zero would be slightly better - NaN usually breaks everything it touches and then you can trace back to when the result first became NaN.
While zero is incredibly common value, and is often a technically valid result, except not being logically valid in the context. Usually zero doesn't produce any noticeable bugs until after release.

So, in Debug mode (when DEBUG is defined) and arguably in Release mode as well (maybe provide an optional define like STRICT_VALIDATIONS) there should be exceptions thrown everywhere necessary, in order to catch bugs early. Any invalid input should be highlighted, not concealed.

Support Infinity and NaN

Thank you for the awesome library!

Having a representation of infinity would be really nice, as some algorithms (converted from floating-point math) sometimes turn a bit ugly, requiring hacks like boolean flags or additional checks.

E.g. for Fixed64 it could be:

public const long NaN = -9223372036854775808L;
public const long PositiveInfinity = 9223372036854775807L;
public const long NegativeInfinity = -9223372036854775807L;
public const long MinValue = -9223372036854775806L;
public const long MaxValue = 9223372036854775806L;

The main use for infinity is to guarantee there's never an overflow when dealing with unknown input, e.g. A + B <= PositiveInfinity; A + PositiveInfinity = PositiveInfinity.

Plus, infinity often serves as a perfect initial value for a FindMin algorithm. Of course you could use MaxValue instead, but sometimes you need to factor currentMin as input while searching, and the input needs to behave like infinity if nothing has been found yet.

Finally, together with NaN those constants should correctly cover most edge cases like Sqrt(<0), Log(0), Div(X, 0), Asin(>1), Tan(PiHalf), etc.

What is exactly approximate RcpPolyXX methods in FixedUtils.cs?

Hi. I'm studying fixed point arithmetic and this FixPointCS is excellent material.

My question is, what is RcpPolyXX approximate? 1/x or 1/(x + 1)?

In Div() method, it used with one subtracted value from original value, like int res = FixedUtil.RcpPoly6(n - ONE);, not FixedUtil.RcpPoly(n) so it is quite confusing.

Mod() operation

I'm a bit puzzled, what's the reason for implementing the modulo function this way?

        public static long Mod(long a, long b)
        {
            long di = a / b;
            long ret = a - (di * b);
            return ret;
        }

Isn't it more performant to just use existing % operator?

        public static long Mod(long a, long b)
        {
            long ret = a % b;
            return ret;
        }

As far as I understand, there should not be any difference in result of calculation.

Also, the function needs input check:

            if (b == 0)
            {
                FixedUtil.InvalidArgument("Fixed64.Mod", "b", b);
                return 0;
            }

(b == MinValue case works well with Mod)

CppTest.cpp is stored as UTF16

This is great work!
CppTest.cpp causes error on linux because of its character code. It has BOM so it may be treated correctly on Windows.
iconv -f UTF16 -t UTF8 < CppTest.cpp

Deterministic across all platforms.

Hello, I have a small question about this library.

I read the following in this libraries description:

Deterministic: Operations produce bit-identical results across languages and compilers

I assume this also means that this library is deterministic across all platforms and architectures? For example across the different consoles (XBOX, PS4, etc) and different processors within the PC (AMD, Intel, etc). Is this true?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.