Reputation: 4078
I want to calculate wind_chill by getting temp and wind_speed from user.
All variables are declared as double
.
wind_chill = 35.74 + 0.6215 * temp + (0.4275 * temp - 35.75) * System.Math.Pow(wind_speed, 0.16);
I am getting this O/P:-
Enter temperature and wind Speed: 20 7 wind_chill is:11.03490062551
But I want to print all the decimal number till last without round up.
Expected O/P:-
wind_chill = 11.034900625509998
By declaring variables as decimal
and converting all the values in decimal
:
I am getting this output:
wind_chill = 11.034900625510096
Still not matching with the expected one. I searched But I didn't get my answer.How to get expected output?
Upvotes: 1
Views: 567
Reputation: 1621
You can inspect your calculation to see that the values returned for most of the expression are accurate. The problem is with the accuracy of System.Math.Pow(wind_speed, 0.16);
. If you look at wolframalpha for that input, there are signifcantly more digits provided than the 1.36526100641507
returned by Math.Pow
.
The reason for this is because Math.pow
uses float point types which are inaccurate by design. You may also be able to use BigInteger
and figure out a way to make your equation work with that.
You can resolve this in a couple of ways:
BigInteger
If you do go with the BigDecimal class provided in that answer, you will be able to make use of the method BigDecimal Pow(double basis, double exponent)
to improve the accuracy your calculation.
You can see your calculation with the above class here.
Upvotes: 3
Reputation: 5121
Calculate the value with doubles. It is just that .NET will format the value to 15 characters when printing. Use R format to get all digits.
var wind_chill = WindChillDbl(20.0, 7.0);
Console.WriteLine(String.Format("{0:R}", wind_chill));
public static double WindChillDbl(double temp, double wind_speed)
{
return 35.74 + 0.6215 * temp + (0.4275 * temp - 35.75) * System.Math.Pow(wind_speed, 0.16);
}
"By default, the return value only contains 15 digits of precision although a maximum of 17 digits is maintained internally. If the value of this instance has greater than 15 digits, ToString returns PositiveInfinitySymbol or NegativeInfinitySymbol instead of the expected number. If you require more precision, specify format with the "G17" format specification, which always returns 17 digits of precision, or "R", which returns 15 digits if the number can be represented with that precision or 17 digits if the number can only be represented with maximum precision." MSDN
Upvotes: 4