comparison scripts/general/nextpow2.m @ 31198:863730dd0f83 stable

nextpow2: Fix for input between 0.5 and 1 (bug #62947). * scripts/general/nextpow2.m: Switch to a naïve implementation using log2 with a single output argument and ceil.
author Markus Mützel <markus.muetzel@gmx.de>
date Wed, 24 Aug 2022 17:15:34 +0200
parents 796f54d4ddbf
children 075443476dfb
comparison
equal deleted inserted replaced
31196:4c38cf0ce06c 31198:863730dd0f83
47 47
48 if (! isnumeric (x)) 48 if (! isnumeric (x))
49 error ("nextpow2: X must be numeric"); 49 error ("nextpow2: X must be numeric");
50 endif 50 endif
51 51
52 [f, n] = log2 (abs (x)); 52 n = ceil (log2 (abs (x)));
53 idx = (n == 0); # Find any failures of log2 function (n == 0) 53 n(x == 0) = 0; # special case
54 n(idx) = f(idx); # and copy over value.
55 n(f == 0.5)--;
56 54
57 endfunction 55 endfunction
58 56
59 57
60 %!assert (nextpow2 (16), 4) 58 %!assert (nextpow2 (16), 4)
62 %!assert (nextpow2 (31), 5) 60 %!assert (nextpow2 (31), 5)
63 %!assert (nextpow2 (-16), 4) 61 %!assert (nextpow2 (-16), 4)
64 %!assert (nextpow2 (-17), 5) 62 %!assert (nextpow2 (-17), 5)
65 %!assert (nextpow2 (-31), 5) 63 %!assert (nextpow2 (-31), 5)
66 %!assert (nextpow2 (1:17), [0 1 2 2 3 3 3 3 4 4 4 4 4 4 4 4 5]) 64 %!assert (nextpow2 (1:17), [0 1 2 2 3 3 3 3 4 4 4 4 4 4 4 4 5])
65 %!assert (nextpow2 (0.5), -1)
66 %!assert (nextpow2 (0.6), 0)
67 ## Special cases 67 ## Special cases
68 %!assert (nextpow2 (0), 0) 68 %!assert (nextpow2 (0), 0)
69 %!assert (nextpow2 (1), 0) 69 %!assert (nextpow2 (1), 0)
70 %!assert (nextpow2 (Inf), Inf) 70 %!assert (nextpow2 (Inf), Inf)
71 %!assert (nextpow2 (-Inf), Inf) 71 %!assert (nextpow2 (-Inf), Inf)