Computer Science 15-110, Spring 2010
Class Notes: Data and Expressions (2 of 3)
Data and Expressions (2 of 3)
class MyCode { public static void main(String[] args) { System.out.println(1.2); } }
class MyCode { public static void main(String[] args) { double x = 1.2; System.out.println(2*x); } }
class MyCode { public static void main(String[] args) { int i = 10; double d = 10.0; System.out.println( 10 / 3 ); System.out.println( i / 3 ); System.out.println( d / 3 ); System.out.println( 10 / 3.0 ); System.out.println( i / 3.0 ); } }
class MyCode { public static void main(String[] args) { double d1 = (29.0 / 7.0) * 7.0; double d2 = 29.0; System.out.println(d1 == d2); // false! System.out.println(d2 - d1); // -3.552713678800501E-15 (tiny!) } }
class MyCode {
public static void main(String[] args) {
double d1 = (29.0 / 7.0) * 7.0;
double d2 = 29.0;
System.out.println(d1 == d2); // still false (of course)
// now compare if their difference is very small...
double epsilon = 0.000001;
System.out.println(Math.abs(d2 - d1) < epsilon); // true!
}
}
class MyCode { public static void main(String[] args) { System.out.println(Math.abs(4.2)); // 4.2 System.out.println(Math.abs(-4.2)); // 4.2 System.out.println(Math.min(3.5, 2.5)); // 2.5 System.out.println(Math.min(2.5, 3.5)); // 2.5 System.out.println(Math.max(3.5, 2.5)); // 3.5 System.out.println(Math.max(2.5, 3.5)); // 3.5 // We can use these in expressions, too: double x = Math.min(5, -13); double y = Math.max(x, x/2); double z = Math.abs(x) + Math.abs(y); System.out.println(x); System.out.println(y); System.out.println(z); } }
Some Math methods (like pow and sqrt) do not have int versions:
class MyCode { public static void main(String[] args) { System.out.println(Math.pow(2, 3)); // 8.0 (and not int 8), which is 2^3 System.out.println(Math.sqrt(9)); // 3.0 which is the square root of 9 System.out.println(Math.pow(9, 0.5)); // ditto (why?) } }
class MyCode { public static void main(String[] args) { System.out.println(Math.signum(5)); // 1.0 System.out.println(Math.signum(5.0)); // 1.0 System.out.println(Math.signum(0)); // 0.0 System.out.println(Math.signum(-42.0)); // -1.0 int x = (int)Math.round(3.5); // must cast Math.round's result with (int) to use as an int! int y = (int)Math.round(-3.5); System.out.println(x); // 4 System.out.println(y); // -3 } }
carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem