Saturday 16 July 2016

Simple mulitply and add arithmetics in the Android world



Hi,

As you know there are three types of people in the world, those who can count and those who can't. In an application I'm working on I encountered a really strange problem where I didn't get the expected output. Ok, so I'm apparently in the category of the ones who can't count :crying: . To show the problem in a really cut down example consider the following:


Code:


        private static final String TAG = "Calc";
        private static final int LENGTH = 16;

        private int[] calc(int a, int b, int z) {
                int zz[] = new int[LENGTH];
                for (int i = 0; i < LENGTH; i++) {
                        z = z * a + b;
                        zz[i] = z;
                }
                return zz;
        }

        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                int a = -1;
                int b = 5;
                int z = 3;
                int zz[] = calc(a, b, z);
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < zz.length; i++) {
                        sb.append(zz[i]);
                        sb.append(" ");
                }
                Log.i(TAG, sb.toString());
                Log.i(TAG, Build.FINGERPRINT);
        }


So, which category are you? What output do you expect? Let me share the output from two devices:


Quote:









07-16 21:59:46.778 17050 17050 I Calc : 5 5 5 5 0 0 0 0 5 5 5 5 0 0 0 0
07-16 21:59:46.778 17050 17050 I Calc : OPPO/F1f/F1f:5.1.1/LMY47V/1446204931:user/release-keys





Quote:









07-16 22:04:58.169 12563 12563 I Calc : 5 5 5 5 0 0 0 0 5 5 5 5 0 0 0 0
07-16 22:04:58.169 12563 12563 I Calc : Sony/D6503/D6503:6.0.1/23.5.A.0.575/1719295681:user/release-keys




Very consistent :)

Let me also share the output from an older device with the JIT Dalvik VM (which actually provided the sequence I was expecting):


Quote:









07-16 22:09:33.795 1980 1980 I Calc : 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3
07-16 22:09:33.795 1980 1980 I Calc : SEMC/ST17i_1250-3167/ST17i:4.0.4/4.1.B.0.587/tL1_3w:user/release-keys




Some background info can also be found here:
http://nicklastechnotes.blogspot.se/...r-mistake.html

Have fun! :cool:


/Nicklas



No comments:

Post a Comment