Group Abstract Group Abstract

Message Boards Message Boards

0
|
11.3K Views
|
4 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Finding the molar mass of a compound.

Posted 11 years ago
POSTED BY: Seokin Yeh
4 Replies

Just noticed that ElementData[] can be called with element's number, hence you can consider input of the form $ X_n^m Y_k^l \dots $

Clear[A] ;
A[arg_] := Inner[Times, ElementData[#, "AtomicMass"] & /@ #1, #2, Plus] & @@ 
    Transpose@(List @@ (arg) /. {\!\(\*SubsuperscriptBox[\(x_\), \(z_\), \(y_\)] -> \({y, z}\)\), Subscript[x_, z_] -> {1, z}, x_^y_ -> {y, 1}});
A[\!\(\*SubsuperscriptBox[\(C\), \(4\), \(6\)]\ \*SubsuperscriptBox[\(H\), \(10\), \(1\)]\)]

I.M.

POSTED BY: Ivan Morozov

Thank you for replying. I liked the ChemicalData approach, but I would have to know the names of all the chemical compounds I encounter (and I am quite awful at compound names). However, I did not know that ChemicalData was a function, and I am glad to know it. Thank you.

The wolfram alpha approach. That is sort of cheating. :) And regardless of that fact, it requires internet connection and takes 10 times longer to evaluate.

Ivan, I loved your solution. I can never get the hang of pure functions, but when I see them, they look so elegant. Thank you very much.

POSTED BY: Seokin Yeh

Hi, Seokin,

Not sure that this can be considered as an improvement of your code, but here is my solution:

A = Inner[Times, ElementData[#, "AtomicMass"] & /@ #1, #2, Plus] &  ;
A[{"Carbon", "Hydrogen"}, {4, 10}]

As for fancy user input, you can try something similar to the following:

c = "Carbon" ;
h = "Hydrogen" ;
arg = Transpose@Partition[#, 2] & @ (ToExpression[#] & /@ StringSplit["c 4 h 10"]) ;
A @@ arg

and the final version:

A = Inner[Times, ElementData[#, "AtomicMass"] & /@ #1, #2, Plus] & @@ (
        Transpose@Partition[#, 2] & @ (ToExpression[#] & /@ 
        StringSplit[#])
     )  & ;
A["c 4 h 10"]

Also Characters[] function can be used to form input arg without blanks, but it will split 10 into 1 and 0 :

Characters["c4h10"]

I.M.

POSTED BY: Ivan Morozov

I know that this may feel like it is cheating in some way ;-) but how about making use of WolframAlpha as in

waAMU[compound_String] := 
 WolframAlpha["molar mass of " <> compound, "PodPlaintext"][[2]]

or even shorter, leveraging ChemicalData,

waAMU[compound_String] := ChemicalData[compound, "MolarMass"]
POSTED BY: David Reiss
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard