division calculates a wrong value
이전 댓글 표시
I have this Market class which adjusts the price of two cryptocurrencies. This method allows you to buy the first cryptocurrency by selling the second.
tokenBobtained = abs(obj.supplyB - (obj.k / obj.supplyA));
disp(tokenBobtained) % print 182
obj.supplyB = obj.k / obj.supplyA;
obj.priceB = (transactionVolume * obj.priceA) / tokenBobtained; % ERROR!
tokenBobtained in the example is 182, but in the last line the result of obj.priceB is not the one hoped for.
obj.priceB in the end of execution is 1 but it should be 0.55. The cool thing is that if I replace 182 with "tokenBobtained" in the last line I get 0.55, but in this way it doesn't work! What's the problem?
댓글 수: 3
Dyuman Joshi
2023년 5월 24일
"What's the problem?"
You are asking us to solve something without providing the necessary information.
We can not say what the problem is, as we do not have sufficient information. Please copy paste your whole code or attach it via the paperclip button.
Walter Roberson
2023년 5월 24일
Are any of the fields involved integer data type, such as uint16 ?
Francesco Pio
2023년 5월 24일
이동: Walter Roberson
2023년 5월 24일
답변 (1개)
Walter Roberson
2023년 5월 24일
이동: Walter Roberson
2023년 5월 24일
initialSupply (1,1) uint64 {mustBePositive} = 1
Operations on uint64 return uint64.
Division with integer datatypes round before conversion to integer data type.
댓글 수: 2
Steven Lord
2023년 5월 24일
The k property of the Market class is uint64 and that gets used in the originally posted code.
You could convert those integer values to double before dividing with / or you could use the idivide function, which lets you control how the result is rounded. Though idivide does not allow you to perform the division between a double and a 64-bit integer so unless you need to allow values of k outside the range of a 32-bit integer I'd store that property as a uint32.
Francesco Pio
2023년 5월 25일
카테고리
도움말 센터 및 File Exchange에서 Price Using Monte Carlo Simulation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!