Wednesday, July 15, 2009

Incremental Addition of 2 Float Variables

Yesterday I responded to the following question on http://social.msdn.microsoft.com/ :


I gave the following response:


I should have pointed out that this is not the best piece of code ever written. First, several other responders suggested that the decimal data type should be used instead of the float data type. (By the way, the response immediately following mine was too quickly conceived – the code presented would not build if plugged into a console application.) I agree with using the decimal data type unless there is some reason for the developer having to use floating point numbers. After all, this does appear to be a science/engineering “application,” and you know how scientists and engineers love their floating point numbers! Using the decimal data type would avoid the conflict which the developer experienced between the decimal number system which we humans use, and the binary number system which computers use.
Second, I am not really comfortable with constructing this kind of ‘for loop’. It is too complex for my liking. I have two possible assumptions related to this issue:
(1) The developer is trying to capture a certain number of data points; or
(2) The developer is trying to capture points until the denominator has reached a specific value.

It appears on the surface that the latter is true. However, perhaps the developer just doing this as a way of capturing the required number of data points. Obviously, I don’t really know for sure.

So, with all this in mind, I’ve constructed two possible coding solutions. Both assume that, for some reason, the developer needs to use floating point numbers. You will notice that I’ve used variable name ‘denominator’ instead of ‘loop_index’. I would suggest coming up with a more meaningful name – one that reflects what it really represents in the formula being used.

The first example assumes that the developer is trying to capture a specific number of data points:


The second example assumes that the developer is trying to capture points until the denominator reaches a specific value:

If the developer is allowed to use the decimal data type rather than using float/double, the examples would not change much. However, he/she would not be faced with the rounding issue.
NOTE: If you have trouble seeing one of the above images, just double-click it. Then, when you are done viewing it, click on the 'navigate back' icon on your browser.

No comments:

Post a Comment