Is there a way to solve wrong results when using (mod) operation?
Show older comments
Hi all,
I am working with many (mod) operations to create my own functions in matlab. However, I face a problem of wrong results that are appears. For example,
***** Manuale calculations ***********
temp = (16667 * 16667 * 16667 ) = 4629907412963
temp = = 2533 * 4629907412963 = 11727555477035279
temp = temp % 25000
temp = 10279
***** Matlab calculations ***********
temp = (16667 * 16667 * 16667 )
temp = 2533 * 4.6299e+12
temp = 1.1728e+16
temp = mod (1.1728e+16 , 25000)
temp = 10280
******************************
As you can see, there are two different results even it is just one value! Also I have another
example with a huge difference between the two results.
Is there a convenient way to solve this issue?
Thanks in advance!
9 Comments
Geoff Hayes
on 20 Apr 2014
Hi Abdulatif,
What happens if you cast the numbers (16667,2533) as 64-bit unsigned integers rather than using the default data type of double?
Or perform the mod(*,25000) on every product rather than waiting until the end against the incredibly large number?
Geoff
Abdulatif Alabdulatif
on 24 Apr 2014
Walter Roberson
on 24 Apr 2014
What is your largest possible product?
Abdulatif Alabdulatif
on 24 Apr 2014
Geoff Hayes
on 24 Apr 2014
Edited: Geoff Hayes
on 24 Apr 2014
You can't get the above result because the product exceeds the maximum for a 64-bit unsigned integer (assuming that you have casted the 16667 and 15472 as uint64).
Are you still performing the mod operation with m=25000? If so, while the below is tedious and inefficient, if you don't have access to the symbolic toolbox then it may still do what you need as long as no single product exceeds 18446744073709551615:
x = uint64(16667);
y = uint64(15472);
m = uint64(25000);
z = mod(mod(mod(mod(x*x,m)*x,m)*x,m)*y,m);
Which is equivalent to 16667*16667*16667*16667*15472 mod 25000.
Abdulatif Alabdulatif
on 24 Apr 2014
Geoff Hayes
on 24 Apr 2014
Please see Walter's explanation below. If you are unsure whether you have the symbolic toolbox or not (I don't!) just type ver at the command line and it will list the MATLAB version and all toolbox versions (of those that you have). If you see the symbolic toolbox then you are good to go!
Abdulatif Alabdulatif
on 28 Apr 2014
Abdulatif Alabdulatif
on 28 Apr 2014
Accepted Answer
More Answers (0)
Categories
Find more on Number Theory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!