/* Copyright (c) 2019 Alex Diener This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Alex Diener alex@ludobloom.com */ #ifndef __IntegerFraction_H__ #define __IntegerFraction_H__ #ifdef __cplusplus extern "C" { #endif typedef struct ifrac { int numerator; unsigned int denominator; } ifrac; #define IFRAC(numerator, denominator) ((ifrac) {numerator, denominator}) // Extracts numerator and denominator from IEEE-754 floating point number ifrac ifrac_fromFloat(float value); // Whole number represented by the fraction int ifrac_wholeValue(ifrac fraction); // Numerator as if the whole number was 0 int ifrac_fractionalNumerator(ifrac fraction); // Floating point representation of the entire number float ifrac_floatValue(ifrac fraction); // Floating point representation of only the fractional part of the number float ifrac_floatFraction(ifrac fraction); // Divides numerator and denominator by their greatest common divisor ifrac ifrac_reduce(ifrac fraction); // ifrac_reduce is called on results from all of these functions ifrac ifrac_add(ifrac lhs, ifrac rhs); ifrac ifrac_sub(ifrac lhs, ifrac rhs); ifrac ifrac_mul(ifrac lhs, ifrac rhs); ifrac ifrac_div(ifrac lhs, ifrac rhs); ifrac ifrac_addScalar(ifrac lhs, unsigned int rhs); ifrac ifrac_subScalar(ifrac lhs, unsigned int rhs); ifrac ifrac_mulScalar(ifrac lhs, unsigned int rhs); ifrac ifrac_divScalar(ifrac lhs, unsigned int rhs); // Compares the relative value of lhs and rhs, returning -1 if lhs is lesser, 1 if lhs is greater, and 0 if lhs and rhs are equivalent int ifrac_cmp(ifrac lhs, ifrac rhs); #ifdef __cplusplus } #endif #endif