I added some code to the site to improve the way source code is displayed, both in snippets in my blog and when viewing an entire file directly. I’m adding line numbers on the server-side, but they are in a separate div so you won’t end up copying the line numbers if you copy and paste the code. The syntax highlighting is all done in Javascript by prettify, an open-source library provided by Google. After getting around two annoying jQuery bugs (one which is only present on IE6, and another which was fixed by upgrading to the latest jQuery level) I got it up and running, and it looks like this:
1 2 3 4 5 6 7 8 9 10 11 12
/**
* Returns 1/this.
*
* @throws ArithemeticException if this == 0.
*/
public BigFraction reciprocal()
{
if(numerator.equals(BigInteger.ZERO))
throw new ArithmeticException("Divide by zero: reciprocal of zero.");
return new BigFraction(denominator, numerator, true);
}
Anyway, I figured I’d show off the full-file view with some source code you’re free to use if you want to. You can find the BigFraction class I wrote in Java when working on some Project Euler problems. The class represents a fraction as a ratio of two BigIntegers, so it will never overflow, and there will never be roundoff error. It was fun to write, because it involved lots of math and manipulation of base-2 numbers (especially for the constructors which took one or two double variables), and I’m one of those weirdos who really likes those things. This works in all the Project Euler problems I’ve used it in, and I’ve done some pretty exhaustive ad-hoc testing, but there’s still a good chance I’ve missed a bug or two. Especially since I didn’t bother writing any unit tests or anything (hey, this is spare-time coding!). If you use this and happen to find any bugs, let me know. And of course, I need to close with:
Disclaimer: the BigFraction class is provided as-is with no warranty expressed or implied. If you use it to calculate missile trajectories and end up nuking the wrong city, you shouldn’t come whining to me.