Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating Point Modulo Operation

Tags:

I am trying to implement the range reduction operation for trigonometry. But instead I think it might be better to just perform a modulo pi/2 operation on incoming data. I was wondering what algorithms exist and are efficient for this operation for 32-bit IEEE 754 floating-point?

I have to implement this in assembly, so fmod, division, multiplication, etc. aren't available to me with just one instruction. My processor uses 16-bit words and I have implemented 32-bit floating point addition, subtraction, multiplication, division, square root, cosine, and sine. I just need range reduction (modulus) for inputting values to cosine and sine.

like image 824
Veridian Avatar asked Feb 29 '12 19:02

Veridian


People also ask

What is the result of modulo operation with float operands?

so modulo operation is made for integers, not for floating-point. please comment down your doubts. In result of modulo operation we get value as answer is remainder. If we use float operands we will get floating point value as quotient and the remainder will be zero, which will not generate right answer.

Can You modulo a float in C++?

Can you modulo a float in C++? Sort of. There’s fmod (and fmodf, fmodl) that compute the remainder from dividing two floating point numbers. There are a couple of caveats though. The first and biggest is that conversion to and from floating point is only rarely precise.

How to find the modulus of two floating-point numbers?

Given two floating-point numbers, find the remainder. Try It! A simple solution is to do repeated subtraction. We can use the inbuilt fmod function to find the modulus of two floating-point numbers. ide.geeksforgeeks.org , generate link and share the link here.

What is the use of modulo operator in C?

The modulo operator is used to extract the remainder after performing a division operation on 2 numbers. For example, the modulo of 3/2 is 1 How do I write a C program to multiply two floating point numbers?


1 Answers

I think standard library's fmod() will be the best choice in most cases. Here's a link to a discussion of several simple algorithms.

On my machine, fmod() uses optimized inline assembly code (/usr/include/bits/mathinline.h):

#if defined __FAST_MATH__ && !__GNUC_PREREQ (3, 5) __inline_mathcodeNP2 (fmod, __x, __y, \   register long double __value;                           \   __asm __volatile__                                  \     ("1:    fprem\n\t"                            \      "fnstsw    %%ax\n\t"                             \      "sahf\n\t"                                   \      "jp    1b"                               \      : "=t" (__value) : "0" (__x), "u" (__y) : "ax", "cc");           \   return __value) #endif 

So it actually uses a dedicated CPU instruction (fprem) for the calculation.

like image 117
Michał Kosmulski Avatar answered Sep 18 '22 21:09

Michał Kosmulski