Maximum and Minimum Values For Ints

Maximum and Minimum values for ints

Python 3

In Python 3, this question doesn't apply. The plain int type is unbound.

However, you might actually be looking for information about the current interpreter's word size, which will be the same as the machine's word size in most cases. That information is still available in Python 3 as sys.maxsize, which is the maximum value representable by a signed word. Equivalently, it's the size of the largest possible list or in-memory sequence.

Generally, the maximum value representable by an unsigned word will be sys.maxsize * 2 + 1, and the number of bits in a word will be math.log2(sys.maxsize * 2 + 2). See this answer for more information.

Python 2

In Python 2, the maximum value for plain int values is available as sys.maxint:

>>> sys.maxint
9223372036854775807

You can calculate the minimum value with -sys.maxint - 1 as shown here.

Python seamlessly switches from plain to long integers once you exceed this value. So most of the time, you won't need to know it.

Integer min and max values

Note that a is Integer.MAX_VALUE - 1 and b is Integer.MIN_VALUE + 1. So yes, it is indeed subtracting and adding 1 twice in each case. The book is not wrong, but it's a stupid way of teaching about wrap-around overflow. Just printing Integer.MIN_VALUE - 1 and Integer.MAX_VALUE + 1 would have made the point.

int min = Integer.MIN_VALUE -1; // min is set to Integer.MAX_VALUE by underflow
int max = Integer.MAX_VALUE +1; // max is set to Integer.MIN_VALUE by overflow

From the Java Language Specification, §15.18.2:

If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format.

The JLS is the ultimate authority when it comes to questions like this, but I don't recommend reading it as a way to learn Java. You'd be better off going through the Java Language Tutorial. It's fairly comprehensive and the content is very high quality.

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

but as for this method, I don't understand the purpose of Integer.MAX_VALUE and Integer.MIN_VALUE.

By starting out with smallest set to Integer.MAX_VALUE and largest set to Integer.MIN_VALUE, they don't have to worry later about the special case where smallest and largest don't have a value yet. If the data I'm looking through has a 10 as the first value, then numbers[i]<smallest will be true (because 10 is < Integer.MAX_VALUE) and we'll update smallest to be 10. Similarly, numbers[i]>largest will be true because 10 is > Integer.MIN_VALUE and we'll update largest. And so on.

Of course, when doing this, you must ensure that you have at least one value in the data you're looking at. Otherwise, you end up with apocryphal numbers in smallest and largest.


Note the point Onome Sotu makes in the comments:

...if the first item in the array is larger than the rest, then the largest item will always be Integer.MIN_VALUE because of the else-if statement.

Which is true; here's a simpler example demonstrating the problem (live copy):

public class Example
{
public static void main(String[] args) throws Exception {
int[] values = {5, 1, 2};
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
for (int value : values) {
if (value < smallest) {
smallest = value;
} else if (value > largest) {
largest = value;
}
}
System.out.println(smallest + ", " + largest); // 1, 2 -- WRONG
}
}

To fix it, either:

  1. Don't use else, or

  2. Start with smallest and largest equal to the first element, and then loop the remaining elements, keeping the else if.

Here's an example of that second one (live copy):

public class Example
{
public static void main(String[] args) throws Exception {
int[] values = {5, 1, 2};
int smallest = values[0];
int largest = values[0];
for (int n = 1; n < values.length; ++n) {
int value = values[n];
if (value < smallest) {
smallest = value;
} else if (value > largest) {
largest = value;
}
}
System.out.println(smallest + ", " + largest); // 1, 5
}
}

How to set minimum/maximum value to an Integer variable

I found solution .

package main

import (
"fmt"
"math"
)

func main() {
// Few Examples

// Integer Max
fmt.Printf("Max int64 = %v\n", math.MaxInt64)
fmt.Printf("Max int32 = %v\n", math.MaxInt32)
fmt.Printf("Max int16 = %v\n", math.MaxInt16)

// Integer Min
fmt.Printf("Min int64 = %v\n", math.MinInt64)
fmt.Printf("Min int32 = %v\n", math.MinInt32)

// Float
fmt.Printf("Max flloat64= %v\n", math.MaxFloat64)
fmt.Printf("Max float32= %v\n", math.MaxFloat32)

}

Min and Max in python?

Basically you are asking the user to input ask_user amount of integer numbers and then finding the max number and min number. Although it is not recommended to code as max=0 and min=999, what is happening here is whenever a number greater than the current max value is put in, it replaces the previous max value with k. This is the same for min, whenever a number smaller than current min value is put in, it replaces the current min value with k.

You should actually first get a list of numbers and then use python functions min()/max() to do this. It is a much better way.

Java MAX and MIN value for integers

Integer overflow. If you go outside the bounds of what an Integer can hold it loops back around the other side.

For example try Integer.MAX_VALUE + 1 and see what it gives you.

Find minimum and maximum values input by the user without using an array

Just compare and update if it should be updated:

if (maxValue < 0 || intVal > maxValue) maxValue = intVal;
if (minValue < 0 || intVal < minValue) minValue = intVal;

detail:

if (                 // if
maxValue < 0 // there are no value yet (this is the first value)
|| // or
intVal > maxValue) // new value is larger than current maximum,
maxValue = intVal; // update the maximum

Maximum and minimum value of C types integers from Python

According to: [Python 3.Docs]: Numeric Types - int, float, complex:

Integers have unlimited precision.

Translated to code:

>>> i = 10 ** 100
>>> i
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
>>> len(str(i))
101
>>> i.bit_length()
333

On the other hand, each C type has a fixed size (depending on platform / architecture), as clearly shown in [CPPReference]: Fundamental types.

Since [Python 3.Docs]: ctypes - A foreign function library for Python doesn't mention anything about types limits (note that there is some stuff not documented there), let's find them out manually.

code00.py:

#!/usr/bin/env python3

import sys
from ctypes import c_int8, c_uint8, c_byte, c_ubyte, c_int16, c_uint16, \
c_int32, c_uint32, c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong, \
c_int64, c_uint64, \
sizeof


def limits(c_int_type):
signed = c_int_type(-1).value < c_int_type(0).value
bit_size = sizeof(c_int_type) * 8
signed_limit = 2 ** (bit_size - 1)
return (-signed_limit, signed_limit - 1) if signed else (0, 2 * signed_limit - 1)


def main(*argv):
test_types = (
c_int8,
c_uint8,
c_byte,
c_ubyte,
c_int16,
c_uint16,
c_int32,
c_uint32,
c_int,
c_uint,
c_long,
c_ulong,
c_longlong,
c_ulonglong,
c_int64,
c_uint64,
)
for test_type in test_types:
print("{:s} limits: ({:d}, {:d})".format(test_type.__name__, *limits(test_type)))


if __name__ == "__main__":
print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
64 if sys.maxsize > 0x100000000 else 32, sys.platform))
rc = main(*sys.argv[1:])
print("\nDone.")
sys.exit(rc)

Notes:

  • Code relies on the fact that for a certain integral type, its interval (and limits are interval's endpoints) is:

    • signed (2's complement): [-(2 bit_size - 1), 2 bit_size - 1 - 1]

    • unsigned: [0, 2 bit_size - 1]

  • To check the a type's signum, use -1 (which will automatically be converted to the upper limit (due to wrap around arithmetic) by unsigned types)

  • There are lots of duplicates the output (below), because some types are simply "aliases" to others

  • The rest of your task (creating a function that compares a Python int to the CTypes type limits, and raises an exception if it isn't) is trivial, so I didn't implement it

  • This is for demonstrating purpose only, so I didn't do any argument check

Output:

  • Win:

    • Python pc064 (064bit):

      [cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q052475749]> "e:\Work\Dev\VEnvs\py_pc064_03.09_test0\Scripts\python.exe" ./code00.py
      Python 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)] 064bit on win32

      c_byte limits: (-128, 127)
      c_ubyte limits: (0, 255)
      c_byte limits: (-128, 127)
      c_ubyte limits: (0, 255)
      c_short limits: (-32768, 32767)
      c_ushort limits: (0, 65535)
      c_long limits: (-2147483648, 2147483647)
      c_ulong limits: (0, 4294967295)
      c_long limits: (-2147483648, 2147483647)
      c_ulong limits: (0, 4294967295)
      c_long limits: (-2147483648, 2147483647)
      c_ulong limits: (0, 4294967295)
      c_longlong limits: (-9223372036854775808, 9223372036854775807)
      c_ulonglong limits: (0, 18446744073709551615)
      c_longlong limits: (-9223372036854775808, 9223372036854775807)
      c_ulonglong limits: (0, 18446744073709551615)

      Done.
    • Python pc032 (032bit):

      [cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q052475749]> "e:\Work\Dev\VEnvs\py_pc032_03.10_test0\Scripts\python.exe" ./code00.py
      Python 3.10.1 (tags/v3.10.1:2cd268a, Dec 6 2021, 18:54:59) [MSC v.1929 32 bit (Intel)] 032bit on win32

      c_byte limits: (-128, 127)
      c_ubyte limits: (0, 255)
      c_byte limits: (-128, 127)
      c_ubyte limits: (0, 255)
      c_short limits: (-32768, 32767)
      c_ushort limits: (0, 65535)
      c_long limits: (-2147483648, 2147483647)
      c_ulong limits: (0, 4294967295)
      c_long limits: (-2147483648, 2147483647)
      c_ulong limits: (0, 4294967295)
      c_long limits: (-2147483648, 2147483647)
      c_ulong limits: (0, 4294967295)
      c_longlong limits: (-9223372036854775808, 9223372036854775807)
      c_ulonglong limits: (0, 18446744073709551615)
      c_longlong limits: (-9223372036854775808, 9223372036854775807)
      c_ulonglong limits: (0, 18446744073709551615)

      Done.
  • Nix (Linux - WSL2) - Python pc064:

    (qaic-env) [cfati@cfati-5510-0:/mnt/e/Work/Dev/StackOverflow/q052475749]> python ./code00.py
    Python 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] 064bit on linux

    c_byte limits: (-128, 127)
    c_ubyte limits: (0, 255)
    c_byte limits: (-128, 127)
    c_ubyte limits: (0, 255)
    c_short limits: (-32768, 32767)
    c_ushort limits: (0, 65535)
    c_int limits: (-2147483648, 2147483647)
    c_uint limits: (0, 4294967295)
    c_int limits: (-2147483648, 2147483647)
    c_uint limits: (0, 4294967295)
    c_long limits: (-9223372036854775808, 9223372036854775807)
    c_ulong limits: (0, 18446744073709551615)
    c_long limits: (-9223372036854775808, 9223372036854775807)
    c_ulong limits: (0, 18446744073709551615)
    c_long limits: (-9223372036854775808, 9223372036854775807)
    c_ulong limits: (0, 18446744073709551615)

    Done.


Related Topics



Leave a reply



Submit