Skip to main content

floating point constants question

1 reply [Last post]
thepigs
Offline
Joined: 2007-06-26
Points: 0

Hi,
Sometimes I code my floating point constants readability wise and expect the compiler to reduce them for me eg. in code marked A below. However if I code the constant in the way I think the hardware works the fastest eg. in code marked C, the code IS faster (8x)! What is the reason why the division(s) in A aren't reduced by the compiler to the multiplication in C? Some sort of technical floating point reason ?
Thanks.
Note: I ran with -Xcomp

<br />
public class Main {</p>
<p>	/**<br />
	 * @param args<br />
	 */<br />
	public static void main(String[] args) throws Exception {<br />
		long now = System.nanoTime();<br />
		double d = 1;<br />
		for (int i = 0; i < 100000000; i++) {<br />
		/* A */<br />
			d = d / 1000.0 / 1000.0 / 1000.0;<br />
		}<br />
		System.out<br />
				.println((System.nanoTime() - now) / 1000.0 / 1000.0 / 1000.0);<br />
		now = System.nanoTime();<br />
		d = 1;<br />
		for (int i = 0; i < 100000000; i++) {<br />
		/* B */<br />
			d = d / (1000.0 * 1000.0 * 1000.0);<br />
		}<br />
		System.out<br />
				.println((System.nanoTime() - now) / 1000.0 / 1000.0 / 1000.0);<br />
		now = System.nanoTime();<br />
		d = 1;<br />
		for (int i = 0; i < 100000000; i++) {<br />
		/* C */<br />
			d = d * (1.0 / 1000.0 / 1000.0 / 1000.0);<br />
		}<br />
		System.out<br />
				.println((System.nanoTime() - now) / 1000.0 / 1000.0 / 1000.0);<br />
	}</p>
<p>}<br />

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
mthornton
Offline
Joined: 2003-06-10
Points: 0

In floating point dividing by x and multiplying by 1/x doesn't always produce the same answer. Thus the compiler is not permitted to make the transformation as it could change the result.