Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New section: Checked arithmetic #72

Open
hyrodium opened this issue Feb 12, 2024 · 1 comment
Open

New section: Checked arithmetic #72

hyrodium opened this issue Feb 12, 2024 · 1 comment
Labels
New section New comparison section

Comments

@hyrodium
Copy link
Member

@hyrodium hyrodium added the New section New comparison section label Feb 12, 2024
@KronosTheLate
Copy link
Contributor

Nice. The introduction could include examples to showcase the issue, such as:

"""
Some operations throw overflow warnings:

julia> factorial(21)  # Explicit overflow warning
ERROR: OverflowError: 21 is too large to look up in the table; consider using `factorial(big(21))` instead
Stacktrace:
 [1] factorial_lookup
   @ Base ./combinatorics.jl:19 [inlined]
 [2] factorial(n::Int64)
   @ Base ./combinatorics.jl:27
 [3] top-level scope
   @ REPL[28]:1

julia> parse(Int32, bitstring(typemax(Int64)))
ERROR: OverflowError: overflow parsing "0111111111111111111111111111111111111111111111111111111111111111"
Stacktrace:
 [1] tryparse_internal(::Type{Int32}, s::String, startpos::Int64, endpos::Int64, base_::Int64, raise::Bool)
   @ Base ./parse.jl:169
 [2] parse(::Type{Int32}, s::String; base::Nothing)
   @ Base ./parse.jl:254
 [3] parse(::Type{Int32}, s::String)
   @ Base ./parse.jl:253
 [4] top-level scope
   @ REPL[35]:1

However, these check slow down computation, and are therefore not done for simple operations like addition and exponentiation, as it would slow down all such computations:

julia> typemax(Int) + 1
-9223372036854775808

julia> 10 ^ round(log10(typemax(Int)), RoundUp)  # log10 returns float, no problem
1.0e19

julia> 10 ^ round(Int, log10(typemax(Int)), RoundUp)  # integer exponent and base -> integer result -> overflow
-8446744073709551616

Some issues can be solved by using BigInt and BigFloat, but there are still no guarantees. If you want to guarantee that overflow never occurs in your program, there are packages that can help. Options include:
"""

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
New section New comparison section
Projects
None yet
Development

No branches or pull requests

2 participants