Jump to content

dealing with unprecision of calculations with decimals


Recommended Posts

Try this script:

$original = "130102.123456"
$diff = "0.000001"
$expected_result = "130102.123455"

consolewrite((($original - $diff) = $expected_result) & @CRLF)

You will get a "False" because the internal result is something near to "130102.123455000001".

This is because of unprecision when dealing with decimals in a binary underlying system (all computers).

The thing that I unexpected is that if you show the result in console or msgbox you'll see exactly "130102.123455".  Why?

PS: these numbers are timestamps. I'm just testing to find a timestamp format that balance precision and human readability

Link to comment
Share on other sites

 

If you force strings for input then forcing string comparison on result could satisfy your needs.

consolewrite((($original - $diff) == $expected_result) & @CRLF)

Interesting!

Anyway I wrongly set the variable declarations as string, I wanted to use this:

$original = 130102.123456
$diff = 0.000001
$expected_result = 130102.123455

consolewrite((($original - $diff) = $expected_result) & @CRLF)

and it still returns "False"    :(

Link to comment
Share on other sites

Use the Round function to control the number of deciminal places returned from a calculation.

Local $original        = 130102.123456
Local $diff            = 0.000001
Local $expected_result = 130102.123455

ConsoleWrite($original & " - " & $diff & " = " & $original - $diff & " (expected: " & $expected_result & ")" & @CRLF)
ConsoleWrite(($original - $diff = $expected_result) & @CRLF)
ConsoleWrite((Round($original - $diff, 6) = $expected_result) & @CRLF)

Edit: Added this example. Note Round added to calculation, not to the Hex conversion.

ConsoleWrite("0.2       = " & Hex(0.2) & @LF)
ConsoleWrite("1.6 - 1.4 = " & Hex(Round(1.6 - 1.4, 1)) & @LF)
Edited by Malkey
Link to comment
Share on other sites

Imbuter2000,

Welcome to the wonderful world of binary floating-point calculations!

There is nothing surprising in what you show, as the following shows:

ConsoleWrite("1.6 = " & Hex(1.6) & @LF)
ConsoleWrite("1.4 = " & Hex(1.4) & @LF)
ConsoleWrite("0.2 = " & Hex(0.2) & @LF)
ConsoleWrite("1.6 - 1.4 = " & Hex(1.6 - 1.4) & @LF)

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Welcome to the wonderful world of binary floating-point calculations!

It's a lie, it's not a wonderful world!

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

What? A surprise every 3 operations, and more with every comparison. Isn't that wonderful?

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Once you can explain why this code outputs what it does for both cases, you are not far from the bare minimum you need to know about numeric bases in programming. The problem is less to do with IEEE754 and the details about floating point, but more about binary itself:

Local $i = 1.1

For $n = 1 To 20
    $i = ($i - 1.0) * 11.0

    ConsoleWrite($i & @LF)
Next


ConsoleWrite("--------------------" & @LF)


Local $i = 1.25

For $n = 1 To 20
    $i = ($i - 1.0) * 5.0

    ConsoleWrite($i & @LF)
Next

It's not a lack of precision, if you used a million decimal places then the first loop would eventually diverge from 1.1, whereas the second loop would never diverge (unless something went horribly wrong). Greater precision just hides the problem.

Link to comment
Share on other sites

Exactly

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...