Issue with "CDbl" function while subtract values of two textboxes - vb.net

I am trying to subtract the value from two textboxes in Visual Studio 2012.
Example input and results:
textbox1 - textbox2 = label1
25.9 - 25.4 = 0.50 (it's ok)
173.07 - 173 = 0.06 (should be 0.07)
144.98 - 142.12 = 2.85 (should be 2.86)
My code (I tried all three lines separately):
label1.text = (Convert.ToDouble(textbox1.text) - Convert.ToDouble(textbox2.text)).ToString
label1.text = (CDbl(textbox1.text) - CDbl(textbox2.text)).ToString
label1.text = (Val(textbox1.text) - Val(textbox2.text)).ToString
This error (may be not an error) occurs some times, not every time.
What am I missing here? And what should I use instead of "CDbl" ?

what should I use instead of "CDbl" ?
When you start with the a string, the best option is Double.Parse() or Double.TryParse(), depending on the possibility for bad data.
But even that's not enough in this case. Computers use something called IEEE754 for floating point arithmetic. This scheme for encoding floating point numbers is designed as an efficient way to represent numbers in binary, and further has direct support in CPUs for arithmetic operations, meaning it is much faster than any available alternative (it's not even close). Pretty much every programming platform uses it.
The downside is there is some loss of precision. When treated as IEEE754 doubles, 173.07-173 produces .69999999.
You can solve this in two ways:
Round the results. This isn't an option when using division, but with just addition and subtraction you can track significant digits and round to get exact results. This is a pain, though.
Use the Decimal type. Decimal isn't perfect, but is does have a much greater degree of precision (at the cost of some performance), and for your sample data produces exact results.
In short, try this code:
label1.text = (Decimal.Parse(textbox1.text) - Decimal.Parse(textbox2.text)).ToString()

Related

How to handle precision problems of floating point numbers?

I am using Firebird 3.0.4 (both in Windows and Linux) and I have the following procedure that clearly demonstrates my problem with floating point numbers, and that also demonstrates a possible workaround:
create or alter procedure test_float returns (res double precision,
res1 double precision,
res2 double precision)
as
declare variable z1 double precision;
declare variable z2 double precision;
declare variable z3 double precision;
begin
z1=15;
z2=1.1;
z3=0.49;
res=z1*z2*z3; /* one expects res to be 8.085, but internally, inside the procedure
it is represented as 8.084999999999.
The procedure-internal representation is repaired when then
res is sent to the output of the procedure, but the procedure-internal
representation (which is worng) impacts the further calculations */
res1=round(res, 2);
res2=round(round(res, 8), 2);
suspend;
end
On can see the result of the procedure with:
select proc.res, proc.res1, proc.res2
from test_float proc
The result is
RES RES1 RES2
8,085 8,08 8,09
But one can expect that RES2 should be 8.09.
One can clearly see that the internal representation of the res contains 8.0849999 (e.g. one can assign res to the exception message and then raise this exception), it is repaired during output but it leads to the failed calculations when such variable is used in the further calculations.
RES2 demonstrates the repair: I can always apply ROUND(..., 8) to repair the internal representation. I am ready to go with this solution, but my question is - is it acceptable workaround (when the outer ROUND is with strictly less than 5 decimal places) or is there better workaround.
All my tests pass with this workaround, but the feeling is bad.
Of course, I know the minimum that every programmer should know about floats (there is article about that) and I know that one should not use double for business calculations.
This is an inherent problem with calculating with floating point numbers, and is not specific to Firebird. The problem is that the calculation of 15 * 1.1 * 0.49 using double precision numbers is not exactly 8.085. In fact, if you would do 8.085 - RES, you'd get a value that is (approximately) 1.776356839400251e-015 (although likely your client will just present it as 0.00000000).
You would get similar results in different languages. For example, in Java
DecimalFormat df = new DecimalFormat("#.00");
df.format(15 * 1.1 * 0.49);
will also produce 8.08 for exactly the same reason.
Also, if you would change the order of operations, you would get a different result. For example using 15 * 0.49 * 1.1 would produce 8.085 and round to 8.09, so the actual results would match your expectations.
Given round itself also returns a double precision, this isn't really a good way to handle this in your SQL code, because the rounded value with a higher number of decimals might still yield a value slightly less than what you'd expect because of how floating point numbers work, so the double round may still fail for some numbers even if the presentation in your client 'looks' correct.
If you purely want this for presentation purposes, it might be better to do this in your frontend, but alternatively you could try tricks like adding a small value and casting to decimal, for example something like:
cast(RES + 1e-10 as decimal(18,2))
However this still has rounding issues, because it is impossible to distinguish between values that genuinely are 8.08499999999 (and should be rounded down to 8.08), and values where the result of calculation just happens to be 8.08499999999 in floating point, while it would be 8.085 in exact numerics (and therefor need to be rounded up to 8.09).
In a similar vein, you could try to use double casting to decimal (eg cast(cast(res as decimal(18,3)) as decimal(18,2))), or casting the decimal and then rounding (eg round(cast(res as decimal(18,3)), 2). This would be a bit more consistent than double rounding because the first cast will convert to exact numerics, but again this has similar downside as mentioned above.
Although you don't want to hear this answer, if you want exact numeric semantics, you shouldn't be using floating point types.

How does VB.NET 2008 round off integer numbers? [duplicate]

According to the documentation, the decimal.Round method uses a round-to-even algorithm which is not common for most applications. So I always end up writing a custom function to do the more natural round-half-up algorithm:
public static decimal RoundHalfUp(this decimal d, int decimals)
{
if (decimals < 0)
{
throw new ArgumentException("The decimals must be non-negative",
"decimals");
}
decimal multiplier = (decimal)Math.Pow(10, decimals);
decimal number = d * multiplier;
if (decimal.Truncate(number) < number)
{
number += 0.5m;
}
return decimal.Round(number) / multiplier;
}
Does anybody know the reason behind this framework design decision?
Is there any built-in implementation of the round-half-up algorithm into the framework? Or maybe some unmanaged Windows API?
It could be misleading for beginners that simply write decimal.Round(2.5m, 0) expecting 3 as a result but getting 2 instead.
The other answers with reasons why the Banker's algorithm (aka round half to even) is a good choice are quite correct. It does not suffer from negative or positive bias as much as the round half away from zero method over most reasonable distributions.
But the question was why .NET use Banker's actual rounding as default - and the answer is that Microsoft has followed the IEEE 754 standard. This is also mentioned in MSDN for Math.Round under Remarks.
Also note that .NET supports the alternative method specified by IEEE by providing the MidpointRounding enumeration. They could of course have provided more alternatives to solving ties, but they choose to just fulfill the IEEE standard.
Probably because it's a better algorithm. Over the course of many roundings performed, you will average out that all .5's end up rounding equally up and down. This gives better estimations of actual results if you are for instance, adding a bunch of rounded numbers. I would say that even though it isn't what some may expect, it's probably the more correct thing to do.
While I cannot answer the question of "Why did Microsoft's designers choose this as the default?", I just want to point out that an extra function is unnecessary.
Math.Round allows you to specify a MidpointRounding:
ToEven - When a number is halfway between two others, it is rounded toward the nearest even number.
AwayFromZero - When a number is halfway between two others, it is rounded toward the nearest number that is away from zero.
Decimals are mostly used for money; banker’s rounding is common when working with money. Or you could say.
It is mostly bankers that need the
decimal type; therefore it does
“banker’s rounding”
Bankers rounding have the advantage that on average you will get the same result if you:
round a set of “invoice lines” before adding them up,
or add them up then round the total
Rounding before adding up saved a lot of work in the days before computers.
(In the UK when we went decimal banks would not deal with half pence, but for many years there was still a half pence coin and shop often had prices ending in half pence – so lots of rounding)
Use another overload of Round function like this:
decimal.Round(2.5m, 0,MidpointRounding.AwayFromZero)
It will output 3. And if you use
decimal.Round(2.5m, 0,MidpointRounding.ToEven)
you will get banker's rounding.

Precise Multiplication

first post!
I have a problem with a program that i'm writing for a numerical simulation and I have a problem with the multiplication. Basically, I am trying to calculate:
result1 = (a + b)*c
and this loops thousands of times. I need to expand this code to be
result2 = a*c + b*c
However, when I do that I start to get significant errors in my results. I used a high precision library, which did improve things, but the simulation ran horribly slow (the simulation took 50 times longer) and it really isn't a practical solution. From this I realised that it isn't really the precision of the variables a, b, & c that is hurting me, but something in the way the multiplication is done.
My question is: how can I multiply out these brackets in way so that result1 = result2?
Thanks.
SOLVED!!!!!!!!!
It was a problem with the addition. So i reordered the terms and applied Kahan addition by writing the following piece of code:
double Modelsimple::sum(double a, double b, double c, double d) {
//reorder the variables in order from smallest to greatest
double tempone = (a<b?a:b);
double temptwo = (c<d?c:d);
double tempthree = (a>b?a:b);
double tempfour = (c>d?c:d);
double one = (tempone<temptwo?tempone:temptwo);
double four = (tempthree>tempfour?tempthree:tempfour);
double tempfive = (tempone>temptwo?tempone:temptwo);
double tempsix = (tempthree<tempfour?tempthree:tempfour);
double two = (tempfive<tempsix?tempfive:tempsix);
double three = (tempfive>tempsix?tempfive:tempsix);
//kahan addition
double total = one;
double tempsum = one + two;
double error = (tempsum - one) - two;
total = tempsum;
// first iteration complete
double tempadd = three - error;
tempsum = total + tempadd;
error = (tempsum - total) - tempadd;
total = tempsum;
//second iteration complete
tempadd = four - error;
total += tempadd;
return total;
}
This gives me results that are as close to the precise answer as makes no difference. However, in a fictitious simulation of a mine collapse, the code with the Kahan addition takes 2 minutes whereas the high precision library takes over a day to finish!!
Thanks to all the help here. This problem was really a pain in the a$$.
I am presuming your numbers are all floating point values.
You should not expect result1 to equal result2 due to limitations in the scale of the numbers and precision in the calculations. Which one to use will depend upon the numbers you are dealing with. More important than result1 and result2 being the same is that they are close enough to the real answer (eg that you would have calculated by hand) for your application.
Imagine that a and b are both very large, and c much less than 1. (a + b) might overflow so that result1 will be incorrect. result2 would not overflow because it scales everything down before adding.
There are also problems with loss of precision when combining numbers of widely differing size, as the smaller number has significant digits reduced when it is converted to use the same exponent as the larger number it is added to.
If you give some specific examples of a, b and c which are causing you issues it might be possible to suggest further improvements.
I have been using the following program as a test, using values for a and b between 10^5 and 10^10, and c around 10^-5, but so far cannot find any differences.
Thinking about the storage of 10^5 vs 10^10, I think it requires about 13 bits vs 33 bits, so you may lose about 20 bits of precision when you add a and b together in result1.
But multiplying them by the same value c essentially reduces the exponent but leaves the significand the same, so it should also lose about 20 bits of precision in result2.
A double significand usually stores 53 bits, so I suspect your results will still retain 33 bits, or about 10 decimal digits of precision.
#include <stdio.h>
int main()
{
double a = 13584.9484893449;
double b = 43719848748.3911;
double c = 0.00001483394434;
double result1 = (a+b)*c;
double result2 = a*c + b*c;
double diff = result1 - result2;
printf("size of double is %d\n", sizeof(double));
printf("a=%f\nb=%f\nc=%f\nr1=%f\nr2=%f\ndiff=%f\n",a,b,c,result1,result2,diff);
}
However I do find a difference if I change all the doubles to float and use c=0.00001083394434. Are you sure that you are using 64 (or 80) bit doubles when doing your calculations?
Usually "loss of precision" in these kinds of calculations can be traced to "poorly formulated problem". For example, when you have to add a series of numbers of very different sizes, you will get a different answer depending on the order in which you sum them. The problem is even more acute when you subtract numbers.
The best approach in your case above is to look not simply at this one line, but at the way that result1 is used in your subsequent calculations. In principle, an engineering calculation should not require precision in the final result beyond about three significant figures; but in many instances (for example, finite element methods) you end up subtracting two numbers that are very similar in magnitude - in which case you may lose many significant figures and get a meaningless answer. Given that you are talking about "materials properties" and "strain", I am suspecting that is actually at the heart of your problem.
One approach is to look at places where you compute a difference, and see if you can reformulate your problem (for example, if you can differentiate your function, you can replace Y(x+dx)-Y(x) with dx * Y(x)'.
There are many excellent references on the subject of numerical stability. It is a complicated subject. Just "throwing more significant figures at the problem" is almost never the best solution.

What is wrong with Math.Round() in VB.Net?

I have encountered a weird case in Math.Round function in VB.Net
Math.Round((32.625), 2)
Result : 32.62
Math.Round((32.635), 2)
Result : 32.64
I need 32.63 but the function is working in different logic in these cases.
I can get the decimal part and make what I want doing something on it. But isn't this too weird, one is rounding to higher, one is rounding to lower.
So how can I get 32.63 from 32.625 without messing with decimal part ? (as the natural logic of Maths)
Math.Round uses banker's rounding by default. You can change that by specifying a different MidPointRounding option. From the MSDN:
Rounding away from zero
Midpoint values are rounded to the next number away from zero. For
example, 3.75 rounds to 3.8, 3.85 rounds to 3.9, -3.75 rounds to -3.8,
and -3.85 rounds to -3.9. This form of rounding is represented by the
MidpointRounding.AwayFromZero enumeration member. Rounding away from
zero is the most widely known form of rounding.
Rounding to nearest, or banker's rounding
Midpoint values are rounded to the nearest even number. For example,
both 3.75 and 3.85 round to 3.8, and both -3.75 and -3.85 round to
-3.8. This form of rounding is represented by the MidpointRounding.ToEven enumeration member.
Rounding to nearest is the standard form of rounding used in financial
and statistical operations. It conforms to IEEE Standard 754, section
4. When used in multiple rounding operations, it reduces the rounding error that is caused by consistently rounding midpoint values in a
single direction. In some cases, this rounding error can be
significant.
So, what you want is:
Math.Round(32.625, 2, MidpointRounding.AwayFromZero)
Math.Round(32.635, 2, MidpointRounding.AwayFromZero)
As others have mentioned, if precision is important, you should be using Decimal variables rather than floating point types. For instance:
Math.Round(32.625D, 2, MidpointRounding.AwayFromZero)
Math.Round(32.635D, 2, MidpointRounding.AwayFromZero)
Try this (from memory):
Math.Round((32.635), 2, MidPointRounding.AwayFromZero)
Try this.
Dim d As Decimal = 3.625
Dim r As Decimal = Math.Ceiling(d * 100D) / 100D
MsgBox(r)
This should do what you want.
Hers a quick function you can add to simplify your life and make it so you don't have to type so much all the time.
Private Function roundd(dec As Decimal)
Dim d As Decimal = dec
Dim r As Decimal = Math.Ceiling(d * 100D) / 100D
Return r
End Function
Add this to your application then use the function
roundd(3.624)
or whatever you need.
to display the result - example
msgbox(roundd(3.625))
This will display a messagebox with 3.63
Textbox1.text = roundd(3.625)
this will set textbox1.text - 3.63 etc. etc.
So if you need to round more then one number, it won't be so tedious and you can save alot of typing.
Hope this helps.
You can't using floats which is what numbers like 32.625 is treated as in VB.Net. (There is also the issue of Banker's rounding as mention by #StevenDoggart - you are probably going to have to deal with both issues.)
The issue is that the number stored is not exactly what is entered because these numbers do not into a fixed binary representation e.g. 32.625 is stored as 32.62499997 and 32.635 as 32.63500001.
The only way to be exact is to store the numbers as the type Decimal
DIM num as Decimal
num = ToDecimal("32.625")

Visual Studio expanding 1.1 to 1.1000000000000001

This is, at least for me, most bizzare Visual Studio 2010 behaviour ever. I'm working on MVC3 project, I copied a line of code from another project (VS2010 also, MVC1 if it matters) which looks like this:
target_height = height * 1.1
when I paste it into MVC3 project, it gets expanded to
target_height = height * 1.1000000000000001
Now, if I type 1.2, it's fine, nothing happens, but if I type 1.12 it is expanded to 1.1200000000000001.
Both target_height and height are integers. Why does one Visual Studio display 1.1 while other expands it to 1.1000000000000001?
What is going on???
I think it is autocomplete went crazy and started fixing floating points constant into "allowed" values. As written in http://accessmvp.com/Strive4Peace/VBA/VBA_L1_02_Crystal.pdf , VB autocomplete really tries to offer only "things that apply specifically to that data type". int * double is understandably not truncated into int * int (automatic conversions always happen only as needed) and what you see is double representation of 1.1 or 1.12 (epsilon = 1.11e-16).
I think it would still need some further checking or verification to learn exact conditions when this happens, but as I am not using VB.NET or MVCx this is not something I am willing to do.
The numerical literal 1.1 does not actually represent the quantity 11/10, but instead represents the quantity round[(2^53*11)/10]/(2^53), which is a tiny bit larger than 11/10. Although that value could be written out precisely as a decimal number with 53 significant figures, doing so would be about as useful as using an inch-denominated measuring tape to determine that something is 1 3/16" long and recording the measurement as 30.1625mm. If one wouldn't be able to distinguish a measurement that was longer or shorter or shorter by less than 1/64", the measurement would be 30.1625mm +/- 0.396875mm, which is functionally the same as 30.2mm +/- 0.4mm.
The fact that Visual Studio would choose to represent the numeric quantity closest to 1.1 as 1.1000000000000001 is curious. On the one hand, the literal 1.1 would be a more concise representation of the same value. On the other hand, even if the aforementioned literal would be indistinguishable from 1.1, the more verbose representation is not without advantage. In some cases, it may be helpful to know whether a quantity is slightly larger or slightly smaller than what it "appears" to be. Even though the difference between the numeric literal 1.1 and the mathematical value 11/10 is numerically insignificant (multiplying the numeric literal by ten yields precisely 11), the difference between (1.1-1.0) and (1/10) is noticeable (multiplying the numeric expression by 10 yields a value greater than one).
1.1 and 1.12 must not have an exact binary representation.
see this : https://stackoverflow.com/questions/634206/what-every-programmer-should-know-about