gnuastro-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[bug #61969] Incorrect output for integer calculations


From: Mohammad Akhlaghi
Subject: [bug #61969] Incorrect output for integer calculations
Date: Tue, 1 Feb 2022 04:58:28 -0500 (EST)

Update of bug #61969 (project gnuastro):

                  Status:                    None => Fixed                  
             Assigned to:                    None => pedram                 
             Open/Closed:                    Open => Closed                 

    _______________________________________________________

Follow-up Comment #3:

That last example was great (and more clear!). Here is the reason behind this
behavior (which is expected, but not intuitive):

Arithmetic reads every number with the smallest possible numerical data type
<https://www.gnu.org/software/gnuastro/manual/html_node/Numeric-data-types.html>
(even accounting for the un-signed nature; when the integer isn't negative!).


Therefore in the last example, both '100' and '4' are read as an unsigned
8-bit integer. Therefore, since both inputs are 'uint8', the output is also
'uint8' and this numeric data type only takes values betweeen 0 to 255.
Therefore, when the value you want to put inside of it is larger, the
remainder of that value and 256 will be written there instead: (300 % 256 =
44). This is called Integer overflow
<https://en.wikipedia.org/wiki/Integer_overflow>. You can see it in practice
with this basic C program:


#include <stdio.h>
#include <stdint.h>

int
main(void)
{
  uint8_t a=100, b=3, c=a*b;
  printf("multiply: %u\n", c);
  return 0;
}


So effectively, this "bug" is the expected behavior! In large data analysis,
this is important because a 100Mb file (that is 'uint8'; like binary maps!)
can become 400Mb if stored as an 'int32'! We don't want to generically read
all small integers as "wider" numbers.

This is something that has been in my mind for a long time! The Good news is
that C library's 'errno.h' has a special error code
<https://www.gnu.org/software/libc/manual/html_node/Error-Codes.html> for such
range overflows: 'ERANGE'. We should add a check for this error code within
arithmetic and if it happens, a warning should be printed that an overflow has
happened (to standard-error; so its even printed with '--quiet'!).

Can you define a task for this Pedram? I am so busy with many meetings today
and am affraid that I may forget.

I will close this bug and we'll follow this in the newly defined task ;-).

    _______________________________________________________

Reply to this item at:

  <https://savannah.gnu.org/bugs/?61969>

_______________________________________________
  Message sent via Savannah
  https://savannah.gnu.org/




reply via email to

[Prev in Thread] Current Thread [Next in Thread]