Newbie: Error in mod evaluation

J

juneappal

Sorry to pester the list with this - it is such a simple problem I
can't figure out what to search for.

This is m first day of playing with Java. I notice that
System.out.println((34/5.0)%1);

evaluates as:

0.7999999999999998

Why is that?
 
A

Andrew Thompson

juneappal said:
Sorry to pester the list ..

usenet newsgroup (specifically). A 'list' generally refers to
a mailing-list, which this is not.
..with this - it is such a simple problem I
can't figure out what to search for.

This is m first day of playing with Java.

I think you'll have a lot of fun. Quick note. A better
group for those just starting in Java/programming is
<http://www.physci.org/codes/javafaq.jsp#cljh>

Though it makes good sense to continue *reading* c.l.j.programmer.
....
0.7999999999999998

The machine representation of floating point numbers is
inherently inaccurate. It is the saem for all programming
languages. The simple fix for Java is to apply a
NumberFormat or DecimalFormat to the output.
<http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormat.html>
<http://java.sun.com/j2se/1.5.0/docs/api/java/text/NumberFormat.html>

HTH
 
R

Roedy Green

Are you sure you meant %?? % is an integer operator.

% is defined for floating point but I think every production use I
have ever seen of it was on ints.
 
R

Roedy Green


quoting from the Java glossary which in turn quotes from the JLS:
http://mindprod.com/jgloss/modulus.html

% is also defined to work with float and double operands, though that
use is quite rare.

The result of a floating-point remainder operation as computed by the
% operator is not the same as that produced by the remainder operation
defined by the IEEE 754 floating point standard. The IEEE 754
remainder operation computes the remainder from a rounding division,
not a truncating division. % on floating-point operations behaves
analogously to the integer remainder operator; this may be compared
with the C library function fmod. The IEEE 754 remainder operation may
be computed by the library routine Math. IEEEremainder. (Note the
violation of the naming conventions.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top