Replacing elements with value is not the same - matlab

I do:
T = inv([1.0 0.956 0.621; 1.0 -0.272 -0.647; 1.0 -1.106 1.703]);
obtaining:
T =
0.2989 0.5870 0.1140
0.5959 -0.2744 -0.3216
0.2115 -0.5229 0.3114
if I do
T(1,1)==0.2989
i obtain
ans =
0
same for other elements.
why this?

Because they are not equal. Its just a display artefact. To see this:
fprintf('%.8f\n', T(1,1))
will give you
0.29893602

MATLAB stores more digits than you usually see. The 0.2989 is actually 0.298936021293776 (and even that is not the end of the story).
Try your code and add
format long
T(1,1)
but still,
T(1,1) == 0.298936021293776
ans =
0
So try
T(1,1) - 0.298936021293776
You just don't see all the digits. T(1,1) is what it is supposed to be.

It's dangerous to test floating point numbers for exact equality. Per default, MATLAB uses 64 bits to store a floating point value, and some values such as 0.1 cannot even exactly be represented by an arbitrary number of bits. T(1,1) is not exactly 0.2989, which you can see when printing the value with a greater precision:
>> T = inv([1.0 0.956 0.621; 1.0 -0.272 -0.647; 1.0 -1.106 1.703])
T =
0.2989 0.5870 0.1140
0.5959 -0.2744 -0.3216
0.2115 -0.5229 0.3114
>> fprintf('%1.10f\n', T(1,1))
0.2989360213
This is why T(1,1) == 0.2989 returns false. It is safer to test whether two floating point values are almost equal, i.e. with regards to a tolerance value tol:
>> tol = 1/1000;
>> abs(T(1,1) - 0.2989) < tol
ans =
1
Here's something you should probably read: click

Related

How to use bitset function in MATLAB to modify multiple bits simultaneously

>> a = 255
a =
255
>> bitset(a,1,0)
ans =
254
here the first bit is set to 0 so we get 11111110 equivalent to 254
>> bitset(a,[1,2],0)
ans =
254 253
here the 1st bit and 2nd bit are being set to 0 seperately. Hence we get
11111110 equivalent to 254
11111101 equivalent to 253
how to get 11111100 equivalent to 252?
Apply bitset twice:
bitset(bitset(a, 1, 0), 2, 0)
The order of application should not matter.
Alternatively, you can use the fact that bitset is an equivalent to applying the correct sequence of bitand, bitor and bitcmp operations.
Since you are interested in turning off multiple bits, you can do
bitand(bitset(a, 1, 0), bitset(a, 2, 0))
Here's a one-liner:
a = 255;
bits = [1,2];
bitand(a,bitcmp(sum(2.^(bits-1)),'uint32'))
Taken apart:
b = sum(2.^(bits-1))
computes the integer with the given bits set. Note that bits must not contain duplicate elements. Use unique to enforce this: bits = unique(bits).
c = bitcmp(b,'uint32')
computes the 32-bit complement of the above. ANDing with the complement resets the given bits.
bitand(a,c)
computes the binary AND of the input number and the integer with the given bits turned off.
Setting bits is easier:
a = 112;
bits = [1,2];
bitor(a,sum(2.^(bits-1)))
Maybe most explicit, easiest to understand, you can convert to a string representing binary and then do the operations there, then convert back.
a = 255
bin_a = flip(dec2bin(a)) % flip to make bigendian
bin_a([1, 2]) = '0'
a = bin2dec(flip(bin_a))
Here is a little recursive function based on the answer from #Mad Physicist that will allow zeroing of any number of bits in data . Thanks for the original info. The recursion is probably dead obvious to most people but it might help somebody out.
function y = zero_nbits(x, n)
y = bitset(x, n, 0)
if n > 1
y = zero_nbits(y, n-1);
end
end

Mod function returns 0 for Matlab

I have a problem with the mod function output in Matlab. I am trying to perform some calculations for ECC double and add algorithm. I am reading data from a file and storing it in a variable and then performing some operations. All works smoothly except that I get 0 in temp1 when I use mod(X2,P). However if I put in values stored in X2(3.0323e+153) and P(1.1579e+77) on command window (mod( 3.0323e+153, 1.1579e+77)), I get the correct values. Can anyone please help me? Below is the part of script which is problematic.
P = hex2dec('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F');
line = fread(fileID,[1,67],'*char');
while ~feof(fileID)
PX = line(4:67);
X = hex2dec(PX);
X2 = X^2;
temp1= mod(X2 , P)
end
line = fread(fileID,[1,69],'*char');
end
fclose(fileID);
I think the problem lies with how you're initializing P. From the documentation for hex2dec (emphasis mine):
d = hex2dec('hex_value') converts hex_value to its floating-point integer representation. The argument hex_value is a hexadecimal integer stored as text. If the value of hex_value is greater than the hexadecimal equivalent of the value returned by flintmax, then hex2dec might not return an exact conversion.
And the value of flintmax is:
>> flintmax
ans =
9.007199254740992e+15
Quite a bit smaller than your value for P. In fact, if we use num2hex to look at the two ways you initialize P, you can see a clear difference:
>> P = hex2dec('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F');
>> num2hex(P)
ans =
4ff0000000000000
>> num2hex(1.1579e+77)
ans =
4fefffda293c30de
As it turns out, the inexact conversion done by hex2dec results in a number that evenly divides into 3.0323e+153, thus giving you a remainder of 0:
>> mod(3.0323e+153, P)
ans =
0
>> mod(3.0323e+153, 1.1579e+77)
ans =
8.795697942083107e+76

Add 1 to the least significant digit of a number in MATLAB

Example: 6.321: I need it to be 6.322.
5.14875: I need it to be 5.14876.
How can I do this?
If you represent numbers as floating point or double precision floating point, this problem is a disaster.
If you can read in a number as a string (you mentioned get the number with the input command), you could do:
x = input('ENTER A NUMBER: ','s');
decimal_place = find(fliplr(x)=='.',1) - 1;
x_val = str2double(x);
if(~isempty(decimal_place))
y = x_val + 10 ^ -decimal_place;
else % if there is no decimal place, find first non-zero digit to get sigfig
warning('ambiguous number of significant digits');
first_nonzero_digit = find(fliplr(x)~='0',1);
if(~isempty(first_nonzero_digit))
y = x_val + 10 ^ (first_nonzero_digit - 1);
else
y = x_val + 1;
end
end
disp('your new number is');
disp(y);
Example test runs:
ENTER A NUMBER: 1.9
your new number is
2
ENTER A NUMBER: 3510
your new number is
3520
ENTER A NUMBER: 323.4374
your number is
323.4375
ENTER A NUMBER: 0
your number is
1
#AndrasDeak - I think you're right the first time. The hard part is not the rounding - it's defining the "last" decimal.
Since floating point numbers aren't exact, I can't think of a reliable way to find that "last" decimal place - in any language.
There is a very hacky way that comes to mind, though. You could "print" the number to a string, with 31 numbers after the decimal point, then working right from the dot, find the first place with 15 0s. (Since double precision numbers can only stably represent the first 14 decimal places and you get a 15th that varies, 31 decimal place will ALWAYS give you at least 15 0s after the last sig digit.)
>> a = 1.34568700030041234556
a =
1.3457
>> str = sprintf('%1.31', a)
str =
Empty string: 1-by-0
>> str = sprintf('%1.31f', a)
str =
1.3456870003004124000000000000000
>> idx = strfind(str, '000000000000000')
idx =
19
>> b = a*10^(idx(1)-3)
b =
1.3457e+16
>> sprintf('%10.20f', b)
ans =
13456870003004124.00000000000000000000
>> c = b+1
c =
1.3457e+16
>> sprintf('%10.20f', c)
ans =
13456870003004124.00000000000000000000
>> final = floor(c)/10^(idx(1)-3)
final =
1.3457
>> sprintf('%10.31f', final)
ans =
1.3456870003004124000000000000000
I think that's a relatively reliable implementation.
http://www.mathworks.com/matlabcentral/answers/142819-how-to-find-number-of-significant-figures-in-a-decimal-number
assuming your just trying to do regular rounding:
i'd use the round function built into matlab.
let's do your example above..
5.14875 has 5 decimal places and you want it to be converterd to 5.14876.
Lets assume you that the 6th decimal place was 9 (so your number is 5.148759)
%Step 1:changethe format so that your going to be able to see all of the
%decimal places
format long
%step2:now enter the original number
OriginalNumber=5.148755
%step 3 take the original number and round it to your new number
NewNumber=round(OriginalNumber,5)
this solution will not work if the 6th number (that you did not show) was a <5 because the computer will not know to round up
assuming your just trying to cut the numbers off...
You cannot do this in regular default matlab floating point numbers. To keep my explination simple I'll just state that without an explination. I'd do some review on the different ways matlab stores # (int vs floating point) on the matlab website. They have excellent documentation.

Do variables contain extra hidden metadata - aka When is zero not zero (but still is)

I hate having to ask this because I assume the answer must be simple, but I cannot for the life of me seem to track down the source. While trying to rewrite a function I ran across this problem:
a = -j
x = real(a)
y = imag(a)
y/x
Which spits out Inf, unexpectedly for me. However...
a = 0
b = -1
b/a
returns -Inf, like I would expect. Inquiring further, a == x, b == y. Clearly that isn't true however. I finally tracked down the problem to this after a lot of frustration. If the original input for a is instead 0-j (vs. -j) then there is no problem.
Both real(-j) and real(0-j) return zero and test as zero, but obviously seem to retain some metadata relating to their origin that I absolutely cannot discover. What precisely am I missing here? It will feel downright wrong if I have to solve this with something like if (x == 0) then x = 0;
Not metadata, just the sign bit of the double precision float.
>> a = 0-j;
>> b = -j;
>> ra = real(a)
ra =
0
>> rb = real(b)
rb =
0
>> ra==0
ans =
1
>> isequal(ra,rb)
ans =
1
Looks the same so far. However, the difference is that with b, we set the sign bit for both the real and imaginary parts when we do -j = -complex(0,1) vs. 0-j = complex(0,-1) (see Creating Complex Numbers). Looking deeper with typecast, which does no conversion of the underlying data:
>> dec2bin(typecast(ra,'uint64'),64)
ans =
0000000000000000000000000000000000000000000000000000000000000000
>> dec2bin(typecast(rb,'uint64'),64)
ans =
1000000000000000000000000000000000000000000000000000000000000000
That 1 is bit 63 (of 0) in the IEEE 754 double precision floating point representation:
Voila! -0 exists in MATLAB too!
When using IEEE 754 floating point numbers there is a convention to have a number approaching zero that cannot be represented by the smallest possible float called an underflow where the precision of the number is being lost with each step below the smallest possible float. Some operating systems will consider the underflow to be equal to zero.
I was surprised to be testing some software and find that a threshold test of zero actually went below zero almost as far as the smallest possible negative float.
Perhaps this is why your getting a negative infinity instead of a divide by zero error which I am assuming is the problem your referring to.

Stability (Numerical analysis)

I'm trying to find the max machine number x that satisfies the following equation: x+a=a, where a is a given integer. (I'm not allowed to use eps.)
Here's my code (which is not really working):
function [] = Largest_x()
a=2184;
x=0.0000000001
while (x+a)~=a
x=2*x;
end
fprintf('The biggest value of x in order that x+a=a \n (where a is equal to %g) is : %g \n',a,x);
end
Any help would be much appreciated.
The answer is eps(a)/2.
eps is the difference to the next floating point number, so if you add half or less than that to a float, it won't change. For example:
100+eps(100)/2==100
ans =
1
%# divide by less than two
100+eps(100)/1.9==100
ans =
0
%# what is that number x?
eps(100)/2
ans =
7.1054e-15
If you don't want to rely on eps, you can calculate the number as
2^(-53+floor(log2(a)))
You're small algorithm is certainly not correct. The only conditions where A = X + A are when X is equal to 0. By default matlab data types are doubles with 64 bits.
Lets pretend that matlab were instead using 8 bit integers. The only way to satisfy the equation A = X + A is for X to have the binary representation of [0 0 0 0 0 0 0 0]. So any number between 1 and 0 would work as decimal points are truncated from integers. So again if you were using integers A = A + X would resolve to true if you were to set the value of X to any value between [0,1). However this value is meaningless because X would not take on this value but rather it would take on the value of 0.
It sounds like you are trying to find the resolution of matlab data types. See this: http://www.mathworks.com/help/matlab/matlab_prog/floating-point-numbers.html
The correct answer is that, provided by Jonas: 0.5 * eps(a)
Here is an alternative for the empirical and approximate solution:
>> a = 2184;
>> e = 2 .^ (-100 : 100); % logarithmic scale
>> idx = find(a + e == a, 1, 'last')
idx =
59
>> e(idx)
ans =
2.2737e-013