I have the following code:
let lootBase = Int(pow((Decimal(level + 1)), 3) * 2)
let lootMod = Int(pow(Decimal(level), 2) * 2)
value = Int(arc4random_uniform(UInt32(lootBase)) + lootMod)
I need value to be an Int. The error I get when I try to surround the pow calculation for Int() is:
Cannot invoke initializer for type int with an argument list of type Decimal
How do I use the pow function with Int in Swift 3?
Int does not have an initializer taking Decimal, so you cannot convert Decimal to Int directly with an initializer syntax like Int(...).
You can use pow(Decimal, Int) like this:
let lootBase = Int(pow((Decimal(level + 1)), 3) * 2 as NSDecimalNumber)
let lootMod = Int(pow(Decimal(level), 2) * 2 as NSDecimalNumber)
let value = Int(arc4random_uniform(UInt32(lootBase))) + lootMod
Or else, you can use pow(Double, Double) like this:
let lootBase = Int(pow((Double(level + 1)), 3) * 2)
let lootMod = Int(pow(Double(level), 2) * 2)
let value = Int(arc4random_uniform(UInt32(lootBase))) + lootMod
But, if you only calculate an integer value's power to 2 or 3, both pow(Decimal, Int) and pow(Double, Double) are far from efficient.
You can declared a simple functions like squared or cubed like this:
func squared(_ val: Int) -> Int {return val * val}
func cubed(_ val: Int) -> Int {return val * val * val}
and use them instead of pow(..., 2) or pow(..., 3):
let lootBase = cubed(level + 1) * 2
let lootMod = squared(level) * 2
let value = Int(arc4random_uniform(UInt32(lootBase))) + lootMod
(Assuming level is an Int.)
Int init() method with no parameter is deprecated for Decimal conversion and should be replaced with Int.init(truncating number: NSNumber) like this
let lootMod = Int(truncating: pow(Decimal(level), 2) * 2 as NSDecimalNumber)
Or
let lootMod = Int(truncating: NSDecimalNumber(decimal: pow(Decimal(level), 2) * 2))
Use decimal for both parameters of pow function.
Maybe the second argument of pow that you are providing is treated as Int instead of Decimal.
Try something like this:
let lootMod = Int(pow(Decimal(level), Decimal(2)) * 2)
A little late for an answer, however:
If level is an Int you could cast it to Float and Use powf() instead of pow() :
let lootBase = Int(powf(Float(level) + 1, 3)) * 2
let lootMod = Int(powf(Float(level), 2)) * 2
If you use UInt32 for addition you should cast all variables to UInt32 before you cast the result to Int:
let value = Int(arc4random_uniform(UInt32(lootBase)) + UInt32(lootMod))
PS: I´m not an expert so check yourself if that works as you expect
Related
Well, I wrote this code and I'm trying to implement the zarith library, to have access to bigger integers, otherwise I'm not able to process the algorithm more than when n=25.
let (~~) = Z.of_int
let (&*) = Z.mul
let (&/) = Z.div
let (&-) = Z.sub
let rec s n chamadas =
if n < 0 || n > 10_000 then invalid_arg "ERRO"
else
match n with
| 0 -> (Z.one , chamadas + 1)
| 1 -> (~~ 2, chamadas + 1)
| _ ->
let (~~ resultado, counter) = s (n - 1) (chamadas + 1) in
let (~~ resultado', counter) = sum_s n 1 counter in
(~~ 3 &* ~~ resultado &+ ~~ resultado', counter)
and sum_s n k chamadas =
let rec aux_sum_s n k chamadas =
if n - 2 < 1 || k > n - 2 then
(0, chamadas)
else
let (~~ resultado, counter) = s k chamadas in
let (~~ resultado', counter) = s (n - k - 1) counter in
let (~~ resultado'', counter) = aux_sum_s n (k + 1) counter in
(~~ resultado &* ~~ resultado' &+ ~~ resultado'', counter)
in
aux_sum_s n 1 chamadas
that's what I understood from the documentation
The first character of an infix operator defines its precedence (priority over other operators) and associativity (how operators with equal precedence are grouped). Therefore, your choice of prefixing the operators that work with Zarith numbers with & is probably the worst possible. Not only does it put all arithmetic operators on the same level, so that the multiplication has no precedence over addition, but it also groups them from right to left!
Therefore,
x &* y &+ z
is parsed as,
x &* (y &+ z)
This basically invalidates all your code.
The right way is to append characters to the infix operator, cf. the floating-point operators, e.g., *., +., etc.
So you can either do,
let ( *& ) = Z.mul
let ( /& ) = Z.div
let ( -& ) = Z.sub
or just use the infix operators that are already provided by the Zarith library together with the local opens, e.g.,
Z.(x * y + z)
is the same as,
x *& y *& +& z
provided you have the above bindings. I believe that the former is much easier to read than the latter.
In addition, you have to keep all numbers in Z.t if you will keep converting them back and forth, then you will lose precision with each conversion to int. It would be much easier if you will keep everything in Z.t.
Finally,
let (~~ resultado, counter) = s (n - 1) (chamadas + 1) in
Is not valid OCaml at all, what you wanted to say could be expressed with the following syntactically valid OCaml
let (resultado, counter) = s (n - 1) (chamadas + 1) in
let resultado = ~~resultado in
But it still doesn't make much sense, since your s function returns the value of type Z.t and applying Z.of_int to doesn't make any sense. And using ~~ for Z.of_int is probably also not the best choice of name, as looks very much like negation. Zarith itself, provides the ~$ operator for that.
I am trying to write my first function in sml. It takes a tuple and returns the sum of first element times 10, second element times 6 and the third, and then divides by 10. I don't know what I am doing wrong here I get this error operator and operand do not agree [tycon mismatch].
fun rgb2gray(rgb: (int*int*int))=
let
val x = (#1rgb * 3 )+ (#2rgb * 6 )+ (#3rgb)
in
x=x/10
end
x=x/10 is an equality comparison (and will only be true if x is zero), and / is for dividing reals, not integers.
(+, -, and * are overloaded, but / isn't.)
Integer division is called div, and since the value of the function should be x div 10, you only need to write x div 10, without any =.
It's more common to use pattern matching than selectors for deconstructing structures, and I would write your function like this:
fun rgb2gray (r, g, b) = (r * 3 + g * 6 + b) div 10
Since molbdnilo already provided an answer, here is an alternative way you can do this using records:
type rgb = { r : int, g : int, b : int }
fun rgb2gray (color : rgb) : int =
(#r color * 3 +
#g color * 6 +
#b color) div 10
or equivalently by pattern matching on records:
fun rgb2gray ({ r = r, g = g, b = b } : rgb) : int =
(r * 3 + g * 6 + b) div 10
Records are like tuples, but where their parts are named rather than numbered (hence #r instead of #1). The syntax is a bit more fiddly, but the upside is that you don't accidentally mix two colors up as easily. Perhaps for RGB values it's hard to mix them up anyway, since the notion of R, G and B in that exact order is quite ingrained into a lot of programmers. Still, this is another option.
Since it appears that others have already helped you solve the problem I thought that I would point out that after the end you need an ; after it since the function is done.
After reading several SO posts on the subject I am still confused, mainly concerning to integer and boolean variables/expressions.
A. Integer expressions
Suppose I want to use modulo expression in a floating point computation, what, if any, is the most correct of the following? Is there any difference between C and C++? or should I just trust the compiler to make the correct conversion?
double sign;
int num = rand() % 100;
//want to map odd num to -1.0 and even num to 1.0
//A
sign = -2 * (num % 2) + 1;
//B
sign = -2.0 * (num % 2) + 1;
//C
sign = -2.0 * (num % 2) + 1.0;
//D
sign = -2 * (num % 2) + 1.0;
//E
sign = -2 * (double)(num % 2) + 1;
//F
sign = -2.0 * (double)(num % 2) + 1;
//G
sign = -2.0 * (double)(num % 2) + 1.0;
//H
sign = -2 * (double)(num % 2) + 1.0;
B. Boolean expressions
Can I use a boolean expression, safely, as an element in floating / integer computations without explicit casting? Is there a difference between C and C++?
double d_res = 1.0;
int i_res = 1;
int num = rand() % 10;
d_res = d_res + (num > 5);//or d_res = d_res + (double)(num > 5)?
i_res += (num > 5);//or i_res += (int)(num > 5)?
A. The initialization
double sign = -2 * (num % 2) + 1;
is perfectly well-defined. That's what I'd use; I don't think there's any need to complicate things with extra casts or anything.
C and C++ are well-defined and convenient in their implicit conversions between integer and floating-point types. Explicit conversions are usually not needed. In my experience there are only three things to worry about:
Code like double ratio = 1 / 3 doesn't do what you want; you need to force one of the operands to / to be floating-point. (This has nothing to do with your question, but it's an extremely easy mistake to make.)
Overflow, if one type or the other can't represent the value. (Also not a problem for your example.)
Overzealous compilers. Many compilers will "helpfully" warn you that you might lose precision when converting from double to float, or from a floating-point type to an integer. So you may need explicit casts to silence those warnings.
B. Asking for the numeric value of a Boolean is perfectly well-defined (is guaranteed to give you a nice, clean, 1 or 0), so your second fragment should be fine also. (I know this is true for C, and per a comment below, it's true for C++ also.)
there is an expression (as a part of median calculation):
auto iter1 = std::next(first, floor(size/2) - 1 );
double result = *iter1 + *(iter1 + 1)) / 2;
where the type of the value under iterators is int.
expected result e.g.:
1.5 = (1 + 2 ) / 2
however , in case of values 1 and 2 the result is 1, looks like implicit conversion to int
please explain, what the rule (or my misunderstanding?) is applied here
In your second expression double result = *iter1 + *(iter1 + 1)) / 2;: as per operator precedence, the evaluation of *(iter1 + 1)) / 2 is done first; and since the operands of the / operator are both ints, the sub-expression will result in integer division. The result of the integer division is then added to *iter1.
there is an expression (as a part of median calculation):
double result = *iter1 + *(iter1 + 1)) / 2;
Since the common type of the expression in the right hand side is an int. No conversion is done. Having at least one double will fix you problem. (Also note the parenthesis I added to fit your example).
double result = (*iter1 + static_cast<double>(*(iter1 + 1))) / 2.0;
Why does the exponential operator use float variables in OCaml?
Shouldn't it allow int variables too?
# 3**3;;
Error: This expression has type int but an expression was expected of type
float
Works:
# 3.0**3.0;;
- : float = 27.
So, the existing answers go into how to get around this, but not into why it is the case. There are two main reasons:
1) OCaml doesn't have operator aliasing. You can't have two operators that do the "same thing", but to different types. This means that only one kind of number, integers or floats (or some other representation) will get to use the standard ** interface.
2) pow(), the exponentiation function has historically been defined on floats (for instance, in Standard C).
Also, for another way to get around the problem, if you're using OCaml Batteries included, there is a pow function defined for integers.
You can use int
let int_exp x y = (float_of_int x) ** (float_of_int y) |> int_of_float
There's a similar question: Integer exponentiation in OCaml
Here's one possible tail-recursive implementation of integer exponentiation:
let is_even n =
n mod 2 = 0
(* https://en.wikipedia.org/wiki/Exponentiation_by_squaring *)
let pow base exponent =
if exponent < 0 then invalid_arg "exponent can not be negative" else
let rec aux accumulator base = function
| 0 -> accumulator
| 1 -> base * accumulator
| e when is_even e -> aux accumulator (base * base) (e / 2)
| e -> aux (base * accumulator) (base * base) ((e - 1) / 2) in
aux 1 base exponent