Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java fraction class

 
varun bihani
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what should be the data types of numerator and denominator of java fraction class? should it be int or double/float?
eg 4/5 or 3.4/4.5 ?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you talking about a Java class called Fraction?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I suppose it depends on what the purpose of your Fraction class is. Is your goal to create an exact representation of a fraction like 1/3? Or will you be satisfied with convenient alternatives like 0.3333333333? If it's the former, I would use only exact integer types for the numerator and denominator - int, long, or BigInteger. Floating-point arithmentic frequently has small roundoff errors; it's inherent in the format. If you're OK with approximations - then why do you need ths Fraction class at all? For computations you might just as well convert everything to doubles. However, you may have some other reason for this class, which I am unaware of. Care to provide more details on what you're trying to do?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would be an interesting exercise to have a number class that could store numerator and denominator. Just so

new MyNumber(1).over( new MyNumber(3) ).times( new MyNumber(3) ).equals( new MyNumber(1) )

or maybe

new MyNumber(1, 3).times( 3 ).equals( 1 );

What would you do about that 3.4 and 4.5 in the original post?

new MyNumber( new MyNumber(34, 10), new MyNumber(45, 10) )

Ok, it doesn't look like that much fun after all. There are languages that maintain numbers like that. Anybody ever use one?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Stan James:
There are languages that maintain numbers like that. Anybody ever use one?


I'm currently playing with Squeak, a modern Smalltalk dialect. Smalltalk has a Fraction class and uses it fully transparently since ages.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic