Sorry, I probably wasn't clear enough --- the only reason there exists an arithmetical difficulty in the first place is because we're materializing an intermediate value we don't really care about with any kind of precision and using it to compute a value which needs perfect precision.
The proposed solution is to never mess with division in the first place when computing P&L; operate on "total" values: cost basis, total profit, ....
Edit: and as a super minor point of contention, I don't think it's wrong to call it a technical difficulty. You can represent the involved quantities exactly with a decimal ratio type, and the existence of a technical solution indicates that the problem is at least somewhat technical in nature.
Let's say you buy three shares at prices of $5, $5 and $10. You paid a total of $20 for the three shares.
Now you sell 2 of them for $20 each ($40 in total), and have 1 share remaining. You want to calculate realized P&L using the average cost method. The average cost per share is $20/3, so the P&L is $40-(20/3).
The proposed solution is to never mess with division in the first place when computing P&L; operate on "total" values: cost basis, total profit, ....
Edit: and as a super minor point of contention, I don't think it's wrong to call it a technical difficulty. You can represent the involved quantities exactly with a decimal ratio type, and the existence of a technical solution indicates that the problem is at least somewhat technical in nature.