Questions tagged [math]

The tag has no usage guidance.

Filter by
Sorted by
Tagged with
2
votes
1answer
23 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 ...
0
votes
1answer
24 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 ...
0
votes
1answer
25 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(...
0
votes
1answer
9 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 ...
0
votes
0answers
26 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
1answer
54 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 ...
0
votes
1answer
10 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
2answers
35 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 ...
0
votes
0answers
14 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 ...
0
votes
0answers
9 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
1answer
18 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 &...
1
vote
1answer
34 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.
2
votes
0answers
79 views

How to calculate sine and cosine in Solidity?

How can I calculate sine and cosine? Is there any library?
0
votes
1answer
60 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
1answer
39 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 ...
0
votes
0answers
16 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 = (...
0
votes
1answer
711 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: ...
0
votes
1answer
96 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% ...
1
vote
3answers
299 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 ...
2
votes
1answer
55 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 ...
3
votes
0answers
129 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/...
3
votes
0answers
41 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 ...
0
votes
0answers
15 views

Does it cost more in AMM fees to split a trade into multiple pieces?

Suppose you're trading against an AMM with a static invariant, such as Uniswap v2. I define "static" as meaning the invariant containing no dynamic parameter in the price curve. A good ...
2
votes
1answer
254 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 ...
0
votes
0answers
40 views

Multiply ray with wad to get wad

What's the correct way to multiply a number in ray (1e27) with a number in wad (1e18) to get the result in wad? E.g., I have an interest rate [ray] and a balance [wad] that I am multiplying to get a ...
4
votes
1answer
3k 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 (...
0
votes
1answer
76 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?
0
votes
1answer
43 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%...
3
votes
1answer
299 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 ...
0
votes
1answer
52 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 ...
1
vote
1answer
135 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.
4
votes
1answer
74 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)...
4
votes
1answer
507 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)); ...
2
votes
0answers
35 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....
1
vote
0answers
365 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
0answers
29 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 ...
1
vote
0answers
156 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 ...
0
votes
0answers
43 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 ...
0
votes
0answers
38 views

Calculating price: "Operator / not compatible"

function getLatestPrice() public view returns (int, uint8) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed....
0
votes
1answer
310 views

How can you cheaply choose from a dynamic array randomly, with an oracle generated seed number, in Solidity?

In JS you could use this and call it a day. let randomArrayEntry = myArray[Math.floor(Math.random() * myArray.length)]; However, in Solidity everything is deterministic unless you call an outside ...
1
vote
2answers
143 views

Why DS-Math add WAD/2 or RAY/2 in WAD,RAY multiply function

//rounds to zero if x*y < WAD / 2 function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint x, ...
1
vote
1answer
214 views

How can I use decimal in solidity

how can i calculate: 1083.83 / 8.25 = 131.37. As I see its not possible in simple way. I have tried a lot of math function but not works. Is there any solution for this?
4
votes
0answers
54 views

How can i do 2^0.3 (exponent below 1) using integers?

simple problem, but i can't seem to wrap my head around it in solidity. how can i do 2^0.3 (exponent smaller then 1) in solidity using integers. thanks in advance K.
1
vote
1answer
142 views

Why don't decimals work in solidity?

I've read this question and answer thread about representing decimal values in solidity, and I understand that math is entirely done using fixed-point. However, I'm curious as to why this is the case. ...
18
votes
4answers
13k views

Can't do any integer division

I'm building a new smart contract but really can't figure out how to perform integer division. I know that fixed point numbers haven't been implemented yet but it should be possible to perform 100/3 = ...