# Questions tagged [math]

The tag has no usage guidance.

54 questions
Filter by
Sorted by
Tagged with
10 views

### Why are protocols like Sushiswap using multiplier 1e10 instead of 1e18?

I've been reviewing a protocol that utilizes MULTIPLIER for their calculations which increases the precision because there are no decimal numbers in solidity. That is fine, but I've seen a lot of ...
• 48
19 views

### How to solve linear equations using solidity?

I am setting up a contract which gets initialized with the following parameters: startDate, endDate, startPrice The price at any given points is the line connecting the two points a and b where a*...
43 views

### ABDKMath64x64 function works in local brownie tests and remix kovan deployment, but transaction reverts when trying it on kovan testnet

Me and my team are quite dumbfounded by this issue we have with one of the utility functions we wrote in our contract that make use of the ABDK64x64 library, the code of which can be found below: In ...
30 views

### Complicated ERC20 Arithmetic

I'm trying to compose a formula in Solidity that has a combination of unsigned integers, signed and exponents, however having a hard time figuring out how to do so. The formula would look something ...
• 101
16 views

### broken for loop

can someone let me know what i got wrong in this for loop, if you need the full code let me know. function calculateSplitPercent() public { for(uint256 i = 0; i >= uniqueIdCounter; i++) { ...
26 views

### Percentages in solidity

How would i work out "x is what percent of y" or for example 5 is what percent 10 = 50%. For some reason i just cant wrap my head around it. A clip of my code is below, i want to work out ...
62 views

### Division of big numbers in a smart contract

I am building a function that will payout dividends based on the percentage of tokens owned. function simulateRent() public payable{ uint256 rent_received = msg.value; for (...
24 views

### What is least expensive way to evaluate an arithmetic expression with only addition and subtraction in Solidity?

Given a particular arithmetic expression: bool result = a + b - c > d - e; Where: a, b, c, d, and e are all memory variables of type uint256. b >= c. d >= e. What would be the best way to ...
• 2,670
12 views

### Dividing Uints with precision

I am writing a contract that allows artists to sell nfts through my contract. I need the contract to calculate how much the artist can withdraw based off of how many tokens are minted and keeping in ...
82 views

### Division error getting token value with too many decimals

I am using the method below to get the value of a token, it works very well when the token value is not something very low like \$0.000004101, the problem is in the division of the wBNB / TOKEN reserve,...
16 views

### dealing with rounding for share issuance based on incoming investment size, total shares outstanding, and total equity

This is probably a fairly straightforward question about rounding errors, but it may help for me to add the context in which this is meaningful. struct EntityToBeInvestedIn { bool exists; ...
• 25
149 views

### How to floor or ceil a fixed point number?

Say I have a signed 64.64 fixed point number 18444899399302180000 or 0.9999 in floating point notation. How can I define a floor and ceil function that floors or ceils an int128 signed 64.64 fixed ...
• 230
1 vote
332 views

### How to handle division by zero in solidity?

In popular programming languages dividing by zero results in an exception being thrown such as ZeroDivisionError in python. Does solidity allow for such exception handling? and if so how would I ...
• 230
189 views

### How to convert uint8 to uint256 bitmap in solidity?

Say I have a uint8 with binary value 0000_1001 i.e. 8+1=9 in decimal. How do I convert this uint8 in a gas efficient way to a uint256 which represents a bitmap?, such that in this example the 9th bit(...
• 230
21 views

### Exponent sign not working, only double star instead, why?

Might be a stupid question. I have checked this many times, it seems as if only the following statement works: value = (n**2+n)/2; And not: value = (n^2+n)/2; Since it gives unexpected, strangely ...
41 views

### Curious about the Math that makes Blockchain/Ethereum work ! Any good resources to learn it?

A bit of a background about me ; Computer Engineer but during my studies i didn't dive too deep into the maths , especially the crypto maths that makes the blockchain and cryptography work looking for ...
1 vote
394 views

### What happens if you subtract two uint256 values whose answer is supposed to be negative?

I tried it with uint256 a = 3; uint256 b = 6; log(a - b); // my own function And the logged output was a huge number. Obviously that's a bug. So how do you deal with this situation? check ...
• 155
20 views

### Why does Ethereum project use custom denominations (e.g. "wei") instead of SI prefix standard (e.g. "microETH", "nanoETH")

What was the reasoning behind reinventing denominations instead of using the standard metric prefixes for ETH? 10^(-18) ETH = 1 aETH ("attoETH", not "wei") 10^(-9) ETH = 1 nETH (&...
1 vote
103 views

### Is solidity compiler rounding floating point numbers during the complilation?

I understand you cant represent them while writing the code, but are floating-point numbers rounded during the compilation? Imagine there is an equation in code, that needs some sort of floating-point ...
• 315
17 views

### how can i get accurate results of these operations?

i have a token swap contract that does simple operation, TokenA is 150% of value of TokenB so if i swap 5 of TokenA i get 7.5 of TokenB the problem is that solidity doesn't accept floating point ...
• 15
11 views

### What is a "short commitment" or "short proof"?

I'm trying to understand how RSA accumulators work, and I am unable to find what people mean when they say "short commitment" or "short proof." Does it refer a commitment or proof ...
1 vote
23 views

### Distribution coefficient

I'm building a dapp and I need some help with creating the formula for a "distribution coefficient/index" (my math is rusted). The idea behind it is: There's a total balance. Let's call it &...
• 307
1 vote
165 views

### Multiply number with Pi in solidity

I'm finding a library to implement this formula in solidity. Is there is a library to implement this formula.
• 601
220 views

### How to calculate sine and cosine in Solidity?

How can I calculate sine and cosine? Is there any library?
• 601
148 views

### Calculate Percentage

I want to calculate user reward per day. uint256 totalBalance = 111; uint256 rewardPerDay = 1000; function calculateReward(uint256 userBalance) public view returns (uint256) { uint256 ...
1 vote
157 views

### Why do you have to wrap a uint() around a number when dividing it and there is a reminder?

Why do you have to wrap a uint() around a number when dividing it and there is a reminder? When I do as the code shows below I get no error and the code works fine. function doMath() public pure ...
• 1,333
26 views

### TickMath UniswapV3 library. Trying to understand getSqrtRatioAtTick solidity function inside

Please, I am uncapable of understanding the logic behind getSqrtRatioAtTick function. Is there anyone wise/clever enough for explaining for example this line? if (absTick & 0x4 != 0) ratio = (...
1k views

### How can I calculate mining rewards from the hashrate?

I'm trying to calculate the 24-hour rewards for ethash mining from the numbers at the WhatToMine JSON API. For example, let’s say I want to calculate the 24-hour mining rewards for 1000 Mh/s ethash: ...
• 105
239 views

### Round integer down to nearest 10

Is there a good way of floor rounding a number to the nearest 10 in solidity? I have a function that calculates a percentage of a number but I want only to return multiples of 10. e.g. if it is 12% ...
• 341
1 vote
546 views

### Using SafeMath with older Solidity compiler

I've been told SafeMath doesn't matter. Does SafeMath slow things down, cost more ETH, or does it add an extra level of stability? Will SafeMath be unsupported one day? contract SafeMath { function ...
127 views

### How to add three numbers using safemath?

I know this might sound obvious but in solidity you can never be too sure. Let us say I have three numbers 5, 7 and 8. Can I add them like so: using SafeMath for uint256; 5.add(7.add(8)); // or even ...
• 1,333
136 views

### What are the mechanics of token reflection? [duplicate]

I'm trying to understand the mechanics behind token reflection. This bit here seems to be what most of the ERC20 Tokens having the reflection mechanic are using: https://github.com/reflectfinance/...
• 199
73 views

### How to make a multiplication and division without overflow and any loss of precision in Vyper

How can I calculate X * Y / Z in vyper uint256 without overflow and any loss of precision? I want to build Vyper FullMath library functions similar to the Uniswap V3 FullMath library written in ...
• 116
510 views

### Is the modulo operation cheaper in unchecked arithmetic?

The docs on Solidity v0.8.0 Breaking Changes mention that overflows are now checked by default: Arithmetic operations revert on underflow and overflow. You can use unchecked { ... } to use the ...
• 12.4k
4k views

### Does the unchecked { ... } block apply only to the current function?

Take the following code snippet: pragma solidity ^0.8.0; contract MyContract { function foo() public returns (uint256 result) { // do unsafe work } function bar() public returns (...
• 12.4k
1 vote
168 views

### Do the Solidity v0.8 overflow checks apply to assembly operations too?

Since Solidity v0.8, the compiler has checks for {over,under}flow by default for all arithmetic operations. Do these checks apply to assembly (yul) arithmetic operations too?
• 12.4k
97 views

### Rounding fixed point integers

If I'm using fixed-point arithmetic to represent rates, for example, 2% in ray (27 decimal precision) would be 102000000000000000000000000000. If I had a rate like 101333333333333333333333333333 (1.33%...
• 107
511 views

### Can division underflow or overflow in Solidity?

We know that: Since Solidity v0.8, the compiler has checks for {over,under}flow by default for all arithmetic operations. Division is an arithmetic operation that rounds down to the integer part of ...
• 12.4k
102 views

### Converting to/from per-second and annualized interest rates with BigNumber.js

In the MakerDao contracts, there are conversions between annualized percentage rates and per-second percentage rates. For example, their Stability Fees documentation gives this example: If the ...
• 107
1 vote
206 views

### What's the most efficient way to check if a number is a power of ten in Solidity?

That is, how to check whether a given number is 10, 100, 1000, etc., all the way up to 10**77, which is the highest power of 10 that fits in uint256.
• 12.4k
127 views

### How to take the average of two uint256s without overflowing?

Say you have two uint256 numbers, x, and y. One way to calculate the arithmetic average between them is this: function avg(uint256 x, uint256 y) external returns (uint256 result) { result = (x + y)...
• 12.4k
1k views

### What does "mulmod" do in Solidity?

I've seen mulmod used in Mikhail Vladimirov's Math in Solidity series: function fullMul(uint256 x, uint256 y) public pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); ...
• 12.4k
38 views

### How does addition look like at the opcode level in Solidity v0.8 and above?

In Solidity v0.7 and below, addition was a simple opcode: ADD Which cost 3 gas units and didn't handle overflows, silently returning the overflown value. But Solidity v0.8 made addition overflow-safe....
• 12.4k
1 vote
655 views

### Division and floor rounding with 18 decimals

I am recreating a UNISWAP-like AMM and have encountered problems anytime I want to divide the balances of tokens in my pool. For example: I want to require() that tokens are deposited in the correct ...
1 vote
38 views

### Calculate exponential growth using decimals

Is there any way to calculate the following in Solidity? 468750 * 2.718281828459045 ** (x * 0.003662040962) - 468750 Typically I would convert the decimals using decimal * 10 ** 18 but with the ...
• 385
1 vote
206 views

### How to get the square root of a big number as returned by web3.utils.toBN()?

I'm working with big numbers as returned by web3.utils.toBN(). According to the web3 documentation, this function returns a BN.js instance. However, there doesn't seem to be a square root function on ...
• 113
84 views

### Can't store the value of a math operation. It's always 0

contract MyContract { uint public priceUSD = 1.70 * 10**8; // USD uint public priceEth; ......... function setPrice(uint newPriceUSD) external ownerOnly() returns(uint, uint) { uint ...
• 563
56 views

### Calculating price: "Operator / not compatible"

function getLatestPrice() public view returns (int, uint8) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed....
• 563