Jump to content

Floating numbers issue


Recommended Posts

$i = 2

While $i < 3
    $i += 0.01
    
    If $i == 2.23 Then
        ConsoleWrite($i + 0.01 & @CRLF)
        ConsoleWrite(2.23 + 0.01 & @CRLF)
    EndIf
WEnd

Is it normal?

Edited by MrCreatoR

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

  • Moderators

MrCreatoR,

Quote

Is it normal?

Absolutely - exactly what one would expect with floating number arithmetic.

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

1 hour ago, MrCreatoR said:

Is it normal?

I am sure you are looking for an explanation, not a solution ;). However (for other readers) :

$i = 2
While $i < 3
    $i = Round($i + 0.01, 2)
    If $i = 2.23 Then
        ConsoleWrite($i + 0.01 & @CRLF)
        ConsoleWrite(2.23 + 0.01 & @CRLF)
    EndIf
WEnd

 

Edited by Musashi

Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

Link to comment
Share on other sites

4 hours ago, Melba23 said:

Absolutely

Then how you explain the fact that this happens starting from 2.23 and not earlier?

Check this:

$i = 2

While $i < 3
    $i += 0.01
    ConsoleWrite($i & @CRLF)
WEnd

and then this:

$i = 1

While $i < 2
    $i += 0.01
    ConsoleWrite($i & @CRLF)
WEnd

with the second example this behavior not occurred.

 

3 hours ago, Musashi said:

I am sure you are looking for an explanation, not a solution ;). However (for other readers) :

Another solution(s)...

$i = 2

While $i < 3
    $i = String($i) + 0.01
    
    If $i = 2.23 Then
        ConsoleWrite($i + 0.01 & @CRLF)
        ConsoleWrite(2.23 + 0.01 & @CRLF)
    EndIf
WEnd

 

Edited by MrCreatoR

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

5 hours ago, MrCreatoR said:

Then how you explain the fact that this happens starting from 2.23 and not earlier?

It is not started at 2.23 it already starts before.
You just don't see it because of the internal rounding rules for the string presentation of the numbers:

$i = 1
While $i < 3
    $i += 0.01
    ConsoleWrite(StringFormat("%16s\t%.17f\n", $i, $i))
WEnd

 

So you have several ways to keep the effect of the round-off-error as small as possible.
One solution is to avoid ther error sum up by recalculating every time:

$i = 1
For $x = 1 To 300
    ConsoleWrite(StringFormat("%16s\t%.16f\n", 1 + 0.01 * $x, 1 + 0.01 * $x))
Next


Another one is (as @argumentum already stated) to calculate in a number expression without rounding error (e.g. integer) as long as possible:

$i = 100
While $i < 300
    $i += 1
    ConsoleWrite(StringFormat("%16s\t%.16f\n", $i / 100, $i / 100))
WEnd

 

Edited by AspirinJunkie
Link to comment
Share on other sites

@MrCreatoR :

As  @Melba23 , @argumentum and @AspirinJunkie have pointed out, this is not an internal problem of AutoIt.

For a deeper understanding, the following treatise may be helpful :

This is an edited reprint of the paper "What Every Computer Scientist Should Know About Floating-Point Arithmetic", by David Goldberg, published in the March, 1991 issue of Computing Surveys. Copyright 1991, Association for Computing Machinery, Inc. :

https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

Not necessarily light fare :lol:, but often referenced in discussions regarding 'Floating-Point Arithmetic'.

Edited by Musashi
typo

Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

Link to comment
Share on other sites

A more low-level illustration of what's under the hood:

$n = 0.01 is represented internally by the exact value
+0.0099840000000000002078337502098293043673038482666015625

After performing this loop:

Local $n = 2
For $i = 1 To 23
    $n += 0.01
Next

$n has the exact internal representation
+2.2299999999999950972551232553087174892425537109375

while the value 2.23 is exactly represented internally as
+2.229999999999999982236431605997495353221893310546875
which shows that equality can't be achieved.

Each value shown above results from exactly computing and composing the components (sign, scale, mantissa) of the low-level FP representation.

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...