Math Bug?

Mac OSX specific forum
spacebuddy
Enthusiast
Enthusiast
Posts: 364
Joined: Thu Jul 02, 2009 5:42 am

Math Bug?

Post by spacebuddy »

I have this equation and it always returns 0, not sure if I am doing something wrong.

Answer=(3000/4000) * 20

always returns 0, on my calculator I get 15

I tried this in another language and it also returns 15

Can someone verify this?

Using the latest beta (2) of PB
User avatar
STARGÅTE
Addict
Addict
Posts: 2295
Joined: Thu Jan 10, 2008 1:30 pm
Location: Germany, Glienicke
Contact:

Re: Math Bug?

Post by STARGÅTE »

3000 and 4000 are integers!
So 3000/4000 is 0!
0 * 20 = 0

If 3000/4000 sould be 0.75 you have to use floats:
Answer = (3000.0/4000) * 20
PB 6.01 ― Win 10, 21H2 ― Ryzen 9 3900X, 32 GB ― NVIDIA GeForce RTX 3080 ― Vivaldi 6.0 ― www.unionbytes.de
Lizard - Script language for symbolic calculations and moreTypeface - Sprite-based font include/module
IdeasVacuum
Always Here
Always Here
Posts: 6426
Joined: Fri Oct 23, 2009 2:33 am
Location: Wales, UK
Contact:

Re: Math Bug?

Post by IdeasVacuum »

Not a bug, just syntax. It's written in integers. Try this:

Code: Select all

Answer = (3000.00/4000.00) * 20.00
Debug Answer
For an accurate divide value it's best to doubles. Also, best not to mix integers with doubles, even though the above would be fine with 20 instead of 20.00.
IdeasVacuum
If it sounds simple, you have not grasped the complexity.
User avatar
Demivec
Addict
Addict
Posts: 4283
Joined: Mon Jul 25, 2005 3:51 pm
Location: Utah, USA

Re: Math Bug?

Post by Demivec »

If 'Answer' is not a float then you will get '0' for the answer because it is using integer arithmetic. This is because (3000/4000) is less then 1 and so it is truncated to zero before multiplying it by 20.

If you insist on using an integer type of variable (i.e. byte, word, long, etc.) to hold the result you can rearrange the equation to multiply first and divide last:

Code: Select all

answer = (3000 / 4000) * 20 ; = 0
Debug answer

answer = 20 * 3000 / 4000 ; = 15
Debug answer
spacebuddy
Enthusiast
Enthusiast
Posts: 364
Joined: Thu Jul 02, 2009 5:42 am

Re: Math Bug?

Post by spacebuddy »

Thanks for all the replies, now I understand and it works find :D
Post Reply