I had tried the ^2 in B4A and of course it would not parse it. Then I remembered the Ctrl - Space in the IDE and started looking in the list and saw the Power() function. Been a while since I used the ^2 and I was not thinking right. Seems the older I get the more that happens...
Sub BtnPowerTwo_Click
Dim x As Float
Try
x = reg_x_txt.Text
x = Power(x,2)
reg_x_txt.Text = NumberFormat2(x,1,9,3,False)
Catch
Log(LastException)
End Try
Sub BtnSquareRoot_Click
Dim x As Float
Try
x = reg_x_txt.Text
x = Sqrt(x)
reg_x_txt.Text = NumberFormat2(x,1,9,3,False)
Catch
Log(LastException)
End Try
End Sub
I am calculating the square root of a number and then immediately the square (Power of 2) of the square root result. If I calculate the square root of 2 and then use the result and find the square of it, the result is 1.99999981. Calculating the square root of 3 and then use the result to calculate the square of it yields 3. Same goes for other numbers. Some yield the precise answer after doing SQRT and then POWER while other just don't get back to the original number. I have for SQRT and POWER the number number declared as type FLOAT. Any idea how to solve this?
Use Double instead of Float.
And use NumberFormat or NumberFormat2 to display numbers.
Most decimal numbers have no exact representation in the binary system.
Thanks Klaus - but it seems to me as if the VARs, when declared as type FLOAT, return an accurate result more often than when they are declared as double? Already using NumberFormat2 as per simple code submitted above. Also find the same issue when doing division and then multiplication directly afterwards to try and get back to the original number.
Thanks Klaus - but it seems to me as if the VARs, when declared as type FLOAT, return an accurate result more often than when they are declared as double? Already using NumberFormat2 as per simple code submitted above. Also find the same issue when doing division and then multiplication directly afterwards to try and get back to the original number.
Floating values are never precise in Java. Double is better than Float and is enough for a lot of uses, but as you noticed, it is easy to see that many computations in a row can lead to an inexact result. In all financial apps that I wrote I never used the floating-point arithmetic, only fixed-point arithmetic for exact precision (all values are integers or longs and are divided by 100 just for display; e.g. 10050 = $100.50).
Hopefully Freddy's (Informatix) tip will help you. If not, try this to see if it suits you:
B4X:
Dim x As Double=2
x = Sqrt(x)
Log(x) 'displays 1.4142..
x = Ceil(NumberFormat2(Power(x,2),1,9,3,False))
Log(x) 'displays 2
x=17/7.3
x = Ceil(NumberFormat2(x*7.3,1,9,3,False))
Log(x) 'displays 17