# Homework Help: MATLAB question int8(x)

1. Jul 10, 2011

### GreenPrint

1. The problem statement, all variables and given/known data

"Define an array of the first 10 integers, using the int8 type designation. Use these integers to calculate the first 10 terms in the harmonic series. Explain your results." I don't understand why I get the results I do and was wondering if someone could explain. I know that the int8(x) stores x as an integer as one byte but I still can't seem to explain why I get the results I do. Thanks in advance!

for k=1:10
a(k)=int8(k);
end
b=1./a

b =

1 1 0 0 0 0 0 0 0 0

2. Relevant equations

3. The attempt at a solution

2. Jul 10, 2011

### uart

The harmonic series is : (1 1/2 1/3 1/4 1/5 ...), that is, (1.00 0.50 0.33 0.25 0.20 ...). Obviously it's just rounding to the nearest integer.

3. Jul 11, 2011

### GreenPrint

Thanks. What is the reason in doing this though? I thought all the int8 command did was compress how much space is used for storage. I understand that this will cause less accuracy and round off errors when doing large calculations but I don't understand why it rounded exactly.

4. Jul 11, 2011

### uart

It's a fairly common thing in a lot of computer languages that the "type" of the operands on the RHS of an assignment determine the precision of the operation performed, which is int8 in this case. So even though you haven't explicitly typed "b" as int8 it gets implicitly typed by the assignment.

You get similar things in C and java, where for example the operation x=13/4 returns x=3.0, even when x is of type float (though they would return 3.25 if you entered the expression as 13.0/4 for example).

Pascal however would return 3.25 in either case, because it relies on things other than the types of the LHS to determine the type of the result. Matlab would also return 3.25 if you typed it in with 13 and 4 literally, because it treats everything as a double precision floating point by default (that is whether or not you type 13 or 13.0 it's still type float). If however you entered "x=int8(13);, x/4" then you'd just get the integer result of 3

Being aware of how a language handles this kind of implicit typing of operation results is a really important part of the understanding of any programming language.

Last edited: Jul 11, 2011