SQLite get floor value of an equation - sqlite

this is a simplified part of my query:
select cast(2102.7 * 100000 as integer)
the result is 210269999
I use cast to floor the result and the result should be integer and the value should be 210270000
Why is this happening?
Update
let me ask another way
I have two decimal columns and i want to multiply them and get the floor of the result, for example:
1.2 * 2 = 2.4
floor(2.4) = 2
1.2 * 3 = 3.6
floor(3.6) = 3
this code works
select cast(1.2 * 2 as int)
-------
2
select cast(1.2 * 3 as int)
-------
3
SQLite does not have floor function See. So I am using cast as int. but because of the floating point problems, i cannot get the true floor result for some values, like this
select cast(2102.7 * 100000 as int)
-------
210269999
I dont want to round up the result. and if i use round function as in this, the same problem occurs for some values.
select round(1.2 * 3 - 0.5)
-------
3 (true result)
select round(2102.7 * 100000 - 0.5)
-------
210269999 (false result)
How can I get the true floor for any values?

Related

SICP Exercise 1.16 ... what does "invariant quantity" hint mean?

I see there are a few other questions around this exercise but none specifically are asking what is meant within the hint... "define the state transition in such a way that the product abn is unchanged from state to state".
They also mention that this idea of using an "invariant quantity" is a powerful idea with respect to "iterative algorithms". By the way, this problem calls for the design of a "logarithmic" exponent algorithm that has a space complexity of O(1).
Mainly I just have no idea what is meant by this hint and am pretty confused. Can anyone give me a nudge in what is meant by this? The only thing I can really find about "invariant quantities" are described using examples in physics which only makes this concept more opaque.
Exercise description in full:
Exercise 1.16: Design a procedure that evolves an iterative exponentiation process that uses successive squaring and uses a logarithmic number of steps, as does fast-expt. (Hint: Using the observation that (bn/2)2 = (b2)n/2, keep, along with the exponent n and the base b, an additional state variable a, and define the state transformation in such a way that the product abn is unchanged from state to state.
At the beginning of the process a is taken to be 1, and the answer is given by the value of a at the end of the process. In general, the technique of defining an invariant quantity that remains unchanged from state to state is a powerful way to think about the design of iterative algorithms.)
Thanks in advance.
This is not about any "logarithmic exponentiation", which is a very vague and confusing terminology.
As the quote you provided says, it is about exponentiation function that takes logarithmic number of steps to get its final result.
So we want to develop a function, exp(b,n), which would take O(log n) time to finish.
The numbers involved are all integers.
So how do we calculate bn? We notice that
b^n = b * b * b * b *... * b
`------n times------/ O(n) time process
and, when n is even,
b^n = b * b * b * b * ... * b *
`------n/2 times-----/
b * b * b * b * ... * b
`------n/2 times-----/
= (b^(n/2))^2 ; viewed from the side
= (b^2)^(n/2) ; viewed from above
and when n is odd,
b^n = b * b * b * b * ... * b *
`------n/2 times-----/
b * b * b * b * ... * b *
`------n/2 times-----/
b
`--1 time--/
= (b^(n/2))^2 * b
= (b^2)^(n/2) * b
Note that both expression fall into same category if we write the first one as (b^2)^(n/2) * 1.
Also note that the equation
b^n = (b )^(n ) * { a where a = 1 }
= (b ^2)^(n/2) * { a where a = ... }
= (b' )^(n' ) * { a' }
means that to calculate b^n * a is the same as to calculate b'^n' * a' with the changed values of { b' = b^2 ; n' = n/2 ; a' = {if {n is even} then {a} else {a * b}} }.
So we don't actually compute either of the sides of that equation. Instead we keep the triples { b, n, a } at each step and transform them according to that rule
{ b, n, a } --> { b', n', a' } --> ...
with the initial values of b and n as given to us, and the first a equal to 1; and know that the final result calculated from any of the triples would be the same if we'd actually calculated it somehow. We still don't know how exactly we'd do that; just that it would be the same. That's the "invariant" part.
So what all this is good for? Well, since the chain { n --> n/2 --> ... } will certainly reach a point where n == 1, we know that at that point we can break the chain since
c^1 * d == c * d
and this one simple multiplication of these two numbers will produce the same result as the initial formula.
Which is the final result of the function.
And that's the meaning of the hint: maintain the state of the computation as a (here) triple of numbers (or just three variables named b, n, a), and implement your computation as a chain of state-transforming steps. When the chain is broken according to some test (here, n == 1), we've reached our destination and can calculate the final result according to some simple rule (here, c * d).
This gives us a nice and powerful methodology for problem solving.
Oh, and we also know that the length of that chain of changing states is O(log n), since we halve that n at each step.
when fast-exp execute, the trace looks something like this
b^14 = (b^2)^7 ; where: b' = b^2; a = 1, n = 7
b^14 = (b^2)^6 * b^2 ; where: b' = b^2; a = b^2, n = 6
b^14 = ((b^2)^2)^3 *b^2 ; where: b' = b^2^2 ; a = b^2, n = 3
b^14 = ((b^2)^2)^2 *b^2 *(b^2)^2 ; where: b' = b^2^2; a = b^2*(b^2)^2, n = 2
notice that all these statements have the general form of b^n = b'^n' * a', and this does not change

how many trailing zeros after factorial?

I am trying to do this programming task:
Write a program that will calculate the number of trailing zeros in a
factorial of a given number.
N! = 1 * 2 * 3 * ... * N
Be careful 1000! has 2568 digits.
For more info, see: http://mathworld.wolfram.com/Factorial.html
Examples:
zeros(6) = 1 ->
6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero
zeros(12) = 2 ->
12! = 479001600 --> 2 trailing zeros
I'm confused as one of the sample tests I have is showing this: expect_equal(zeros(30), 7)
I could be misunderstanding the task, but where do the trailing 7 zeros come from when the input is 30?
with scientific notation turned on I get this:
2.6525286e+32
and with it turned off I get this:
265252859812191032282026086406022
What you are experiencing is a result of this: Why are these numbers not equal?
But in this case, calculating factorials to find the numbers of trailing zeros is not that efficient.
We can count number of 5-factors in a number (since there will be always enough 2-factors to pair with them and create 10-factors). This function gives you trailing zeros for a factorial by counting 5-factors in a given number.
tailingzeros_factorial <- function(N){
mcount = 0L
mdiv = 5L
N = as.integer(N)
while (as.integer((N/mdiv)) > 0L) {
mcount = mcount + as.integer(N/mdiv)
mdiv = as.integer(mdiv * 5L)
}
return(mcount)
}
tailingzeros_factorial(6)
#> 1
tailingzeros_factorial(25)
#> 6
tailingzeros_factorial(30)
#> 7

Using function inside constriant block

I am trying to use a function inside constraint block. Randomization happens but the constraints are not being met. I have verified that the function works as expected outside the constraint block. The function uses only function arguments and not any other class members.
local rand logic [6:0] [3:0] [9:0] coeff_mult;
constraint prods_are_multiples {
foreach(coeff_mult[i]) {
get_real(coeff_mult[i][3]) == (-1 * get_real(coeff_mult[i][0]));
get_real(coeff_mult[i][2]) == (-1 * get_real(coeff_mult[i][1]));
get_real(coeff_mult[i][0]) == (3 * get_real(coeff_mult[i][1]));
}
}
function automatic shortreal get_real(input [9:0] val);
shortreal sign;
bit [9:0] magnitude;
sign = -1**(val[9]);
magnitude = ({10{val[9]}} ^ val[9:0]) + val[9];
get_real = sign * (magnitude[9:3] + magnitude[2] * 0.5 + magnitude[1] * 0.25 + magnitude[0] * 0.125);
endfunction
I came across a similar post, but it didnt solve my problem.
Is there anything wrong with the code? If not, is there any other way of doing this?
The post you reference explains the reasoning. The inputs to your function get their random values chosen before calling the function in the constraint. So there are effectively no constraints on coeff_mult before evaluating the equality constraints.
Also, the LRM does not allow expressions of non-integral values in constraints, technically, although some tools allow limited cases.
The best strategy for randomizing real numbers is doing everything with scaled integral values, then converting the resulting values to real (or sign/magnitude) in post_randomize().
I have a working example of your kind of function usage with use of additional random variable. I have checked this with ~10 different seeds and I have also posted constraint results with 1 particular seed.
typedef bit [7:0] tabc;
class t;
rand bit [3:0] a, b;
rand tabc ca;
// Original Constraint : get_b(b) == get_a(a) + 1;
constraint c {
ca == get_b(b);
get_a(a) == ca - 1;
}
function tabc get_a (input bit[3:0] a);
return (tabc'(a + 15));
endfunction
function tabc get_b (input bit[3:0] b);
return (tabc'(b + 10));
endfunction
endclass
program temp();
t t1 = new();
initial
begin
repeat (10) begin
t1.randomize();
$display("t1.a - %0d", t1.a);
$display("t1.b - %0d", t1.b);
end
end
endprogram
// Results -
t1.a - 7
t1.b - 13
t1.a - 2
t1.b - 8
t1.a - 5
t1.b - 11
t1.a - 4
t1.b - 10
t1.a - 0
t1.b - 6
t1.a - 8
t1.b - 14
t1.a - 9
t1.b - 15
t1.a - 6
t1.b - 12
t1.a - 0
t1.b - 6
t1.a - 5
t1.b - 11
I am not quite sure of how this one is different than your method. However I am thinking that without having any random variable in constraints, the solver might have considered as no constraint for any variable and hence it didn't try to solve constraint before the solution.
I tried to insert temporary variable, in order to force solver to look at constraints first.
I am not sure how much correct my explanation is, but atleast it worked for me for some time. You can check it and try to run it with more seeds, before adapting it into your solution.

recursive function to convert string to integer ML

I need to write my own recursive function in ML that somehow uses ord to convert a string of numbers to integer type. I can use helper functions, but apparently I should be able to do this without using one (according to my professor).
I can assume that the input is valid, and is a positive integer (in string type of course).
So, the call str2int ("1234") should output 1234: int
I assume I will need to use explode and implode at some point since ord operates on characters, and my input is a string. Any direction would be greatly appreciated.
Given that you asked, I guess I can ruin all the fun for you. This will solve your problem, but ironically, it won't help you.
Well, the ordinal number for the character #'0' is 48. So, this means that if you subtract of any ordinal representing a digit the number 48 you get its decimal value. For instance
ord(#"9") - 48
Yields 9.
So, a function that takes a given character representing a number from 0-9 and turns it into the corresponding decimal is:
fun charToInt(c) = ord(c) - 48
Supposing you had a string of numbers like "2014". Then you can first explode the string into list of characters and then map every character to its corresponding decimal.
For instance
val num = "2014"
val digits = map charToInt (explode num)
The explode function is a helper function that takes a string and turn it into a list of characters.
And now digits would be a list of integers representing the decimal numbers [2,0,1,4];
Then, all you need is to apply powers of 10 to obtain the final integer.
2 * 10 ^ 3 = 2000
0 * 10 ^ 2 = 0
1 * 10 ^ 1 = 10
4 * 10 ^ 0 = 4
The result would be 2000 + 0 + 10 + 4 = 2014
You could define a helper function charsToInt that processes the digits in the string from left to right.
At each step it converts the leftmost digit c into a number and does addition with the 10x-multiple of n (which is the intermediary sum of all previously parsed digits) ...
fun charsToInt ([], n) = n
| charsToInt (c :: cs, n) = charsToInt (cs, 10*n + ord c - 48)
val n = charsToInt (explode "1024", 0)
Gives you: val n = 1024 : int
As you see the trick is to pass the intermediary result down to the next step at each recursive call. This is a very common technique when dealing with these kind of problems.
Here's what I came up with:
fun pow10 n =
if n = 0 then 1 else 10*pow10(n-1);
fun str2help (L,n) =
if null L then 0
else (ord(hd L)-48) * pow10(n) + str2help(tl L, n-1);
fun str2int (string) =
str2help(explode string, size string -1);
str2int ("1234");
This gives me the correct result, though is clearly not the easiest way to get there.

Separate a number into fixed part

What is the algorithm to find the number way to separate number M to p part and no two part equal.
Example:
M = 5, P = 2
they are (1,4) (2,3). If P = 3 then no partition availabe, i.e
not (1,2,2) because there two 2 in partition.
In the expanded product
(1+x)(1+x2)(1+x3)...(1+xn)
find the coefficient of x^n. This gives the number of any possibility to represent n as sum of different numbers, i.e., a variable number of terms.
You want the number of possibilites to have
n = i1+i2+...+iP with i1 < i2 < ... < iP
which can be realized by setting
i1=j1, i2=i1+j2=j1+j2, ...
iP=iP-1+jP=j1+j2+...+jP with all jk > 0
so that the original task is the same as counting all the ways that one can solve
n = P * j1+(P-1) * j2+...+1 * jP with all jk > 0, but unrelated among each other.
The corresponding generator function is the product of the geometric series of the powers of x, omitting the constant term,
(x+x2+x3+...) * (x2+x4+x6+...) * (x3+x6+x9+...) * ... * (xP+x2*P+x3*P+...)
= xP*(P+1)/2 * (1+x+x2+...) * (1+x2+x4+...) * (1+x3+x6+...) * ... * (1+xP+x2*P+...)
Clearly, one needs n >= P*(P+1)/2 to get any solution at all. For P=3 that bound is n >= 6, so that n=5 has indeed no solutions in that case.
Algorithm
count = new double[N]
for k=0..N-1 do count[k] = 1
for j=2..P do
for k=j..N-1 do
count[k] += count[k-j]
Then count[k] contains the number of combinations for n=P*(P+1)/2+k.

Resources