开发者

Chemical balancer in Java

开发者 https://www.devze.com 2023-02-02 06:54 出处:网络
I\'m making an app for a chemical formula, and I have made it so that it returns double coefficients.

I'm making an app for a chemical formula, and I have made it so that it returns double coefficients.

For example, C6H12O6 + O2 = CO2 + H2O returns .166666667, 1.0, 1.0, and 1.0. I want to write code so that it is 1, 6, 6, and 6 (integers). Also, for another equation, like Ca(OH)2 + H3PO4 = Ca3(PO4)2 + H2O, the return is .5, .3开发者_开发百科33333333, .166666667, and 1.0. It should be 3, 2, 1, and 6. Is there a way I can convert these to integer coefficients in Java?


Do your calculations using a fraction library (like this one by apache). It will keep the results of your calculations as fractions. You can then use Fraction.getDenominator() to find the common one and multiply the rest of your coefficients out by it.


Use the appropriate type. In your case, that would be a fraction type which doesn't exist (in the JDK, Google is your friend), yet. Go to Wikipedia or math.stackexchange.com to freshen up your knowledge about them.

After you did the balancing, use find the smallest common multiple for all denominators to get integer fractions.


Like Aaron suggests, the rational type is not a Java standard one.

However, there are external libraries providing it, like JScience with its Rational type. Unfortunately, there is no information about a potential availability for the Android platform. If it's not the case, try get inspiration from it to create your own rational class.

0

精彩评论

暂无评论...
验证码 换一张
取 消