Floating Point Playground 5 points Computer arithmetic may not behave the same a
ID: 3871795 • Letter: F
Question
Floating Point Playground 5 points Computer arithmetic may not behave the same as we would expect from real arithmetic. For example, if we perform the operation: x= 1 + 10-20 our computer will return the value of x as "1". For this exercise, you will be given a variable a (a random number). Add successively smaller powers of 10 to this number (i.e, compute a 10, a +10, a+ 10, etc.) until the result is unchanged by the addition. Save the last power of 10 that made an impact to the variable k.(.e. if a 10, was different from the original value but a10 produced no change, you would want k to have the value "-5". Be sure to write code that does this in a systematic manner, because the value of a will be different each time. Answer* Press F9 to toggle full-screen mode. Set editor mode in user profileExplanation / Answer
%Matlab code
function k = floatingPointPlayGround(a)
k = 1;
tenPower = 1.0;
while (true)
result = a + (tenPower/10.0);
if (result == a)
break;
end
k++;
end
end
% calling the above function
k = floatingPointPlayGround(1.0)
------------------------------------------------------------------
// Since you didn't specify the language, I wrote the java code too
public class NewClass {
public static int floatingPointPlay(float a) {
int k = 0;
float tenPower = 1.0f;
while (true) {
float result = a + (tenPower/10.0f);
if (result == a) {
break;
}
k++;
}
return k;
}
public static void main(String [] args) {
System.out.println(floatingPointPlay(1.0f));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.