Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use modulus for float/double?

Tags:

java

modulo

I'm creating an RPN calculator for a school project and having trouble with the modulus operator. Since we're using the double data type, modulus won't work on floating-point numbers. For example, 0.5 % 0.3 should return 0.2, but I'm getting a division by zero exception.

The instruction says to use fmod(). I've looked everywhere for fmod(), including javadoc, but I can't find it. I'm starting to think it's a method I'm going to have to create?

Edit: Hmmm, strange. I just plugged in those numbers again and it seems to be working fine… but just in case. Do I need to watch out for using the mod operator in Java when using floating types? I know something like this can't be done in C++ (I think).

like image 288
ShrimpCrackers Avatar asked Jun 01 '10 02:06

ShrimpCrackers


People also ask

Can I use a modulus with a double?

Double Modulus OperatorIf either or both operands of the mod operator have type double, then evaluating it produces the remainder. This kind of mod operator does not exist in C or C++ where the mod operator only works with int operands.

How do you use modulus with float?

The modulus is basically finding the remainder. For this, we can use the remainder() function in C. The remainder() function is used to compute the floating point remainder of numerator/denominator. So the remainder(x, y) will be like below.

Can you use the modulus operator for float variables?

Yes, %(modulo) operator isn't work with floats and double.. if you want to do the modulo operation on large number you can check long long int(64bits) might this help you.

Can modulus operator be used with float Java?

As we learn in first paragraph, in Java modulus, operator can also be applied to floating-point numbers e.g. 3.0%1.0 is perfectly legal in Java. Since it return remainder value in division operation it is also known as remainder operator.


1 Answers

You probably had a typo when you first ran it.

evaluating 0.5 % 0.3 returns '0.2' (A double) as expected.

Mindprod has a good overview of how modulus works in Java.

like image 51
RodeoClown Avatar answered Oct 14 '22 14:10

RodeoClown