The question is very simple: if we type isprime(12646216567629137) matlab answers '0' which means that the number is not prime. But indeed is a prime (tested with Mathematica). So, what's wrong? Could be something related with the digits of the number?

 Akzeptierte Antwort

Dyuman Joshi
Dyuman Joshi am 10 Okt. 2023
Bearbeitet: Dyuman Joshi am 10 Okt. 2023

1 Stimme

Not all numbers can be exactly represented in double precision (which is the default numeric data type in MATLAB). The largest consecutive integer possible in floating point format is
s = flintmax;
fprintf('%d',s)
9007199254740992
which corresponds to 2^53.
What's the distance between p and the next largest representable number?
e = eps(s)
e = 2
Thus, the next value that can be represented in double precision is
S = s + eps(s);
fprintf('%d',S)
9007199254740994
If we add something smaller than eps(s) to s, the result does not changes -
fprintf('%d', s+e-0.2)
9007199254740994
As you can see, this is a limitation of double precision numbers (IEEE 754 standard).
Read more here - double, eps
Alternatively, you can use integers according to the value you have - Data Type - Integers. Note that each integer data types have a limited precision as well.
z1=uint64(12646216567629137)
z1 = uint64 12646216567629137
isprime(z1)
ans = logical
1
In case the value is so large, that none of the numeric data types can store it exactly, you can use symbolic numbers (Note requires Symbolic Math Toolbox)
digits(20)
z2 = sym('12646216567629137')
z2 = 
12646216567629137
isprime(z2)
ans = logical
1
Choosing a 20 digit prime number -
z3 = uint64(975319753197531975319)
z3 = uint64 18446744073709551615
As you can see the stored value is not the same as the value provided.
z4 = sym('975319753197531975319')
z4 = 
975319753197531975319
isprime(z4)
ans = logical
1
When defining symbolic number for a large numerical value, provide the number inside quotation marks.

Weitere Antworten (0)

Kategorien

Mehr zu Discrete Math finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by