Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

leggyguy

My wierd problem

This topic is 5563 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am creating a trendy little baseball sim, and everything is going cool, except I have a problem when I cast ints to doubles. I am trying to calculate avg with this:

double Average = (double)Hits / (double)AtBats;

 
Hits and AtBats are both integers, and of course average is a double. Now, as far as I can see, this should be ok, but when I use printf to print the figure in Average, the printed figure is sometimes the correct figure, and sometimes not. If i run a loop, around half of the figures are right, and half are out by a few percentage points. Anyone have any idea why this is? Pretty sure its not my code, because it is very basic.

Share this post


Link to post
Share on other sites
Advertisement
...???

So if you have 5 Hits and 10 AtBats it will only print "0.5" half of the time? What else does it print? If it''s something like "0.499999999999999" or "0.50000000000001" then it''s a standard "feature" of floating-point numbers : computers make approximation errors constantly when working with them.

ToohrVyk

Share this post


Link to post
Share on other sites
quote:
Original post by ToohrVyk
If it''s something like "0.499999999999999" or "0.50000000000001" then it''s a standard "feature" of floating-point numbers : computers make approximation errors constantly when working with them.


Yep. I''m not familiar with the scoring system in baseball, but if the figure will eventually be expressed as a percentage, then I''d recommend:

(a) using floats rather than doubles
(b) multiplying Hits by 100 before dividing it

Heck, if you do the second of those, you could probably avoid using floating-point numbers altogether.

Superpig
- saving pigs from untimely fates, and when he''s not doing that, runs The Binary Refinery.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!