Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: MATLAB question int8(x)

  1. Jul 10, 2011 #1
    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

    b =

    1 1 0 0 0 0 0 0 0 0

    2. Relevant equations

    3. The attempt at a solution
  2. jcsd
  3. Jul 10, 2011 #2


    User Avatar
    Science Advisor

    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.
  4. Jul 11, 2011 #3
    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.
  5. Jul 11, 2011 #4


    User Avatar
    Science Advisor

    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
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook