#include <cmath> - visual-studio-2010

What is wrong with the code snippet below that VS2010 wouldn't compile it?
int m = sqrt( n );
( I am trying to ascertain whether an integer is prime... )

You need to pass a specific floating point type to sqrt - there's no integer overload. Use e.g:
long double m = sqrt(static_cast<long double>(n));
As you include cmath not math.h I'm assuming you want c++. For C, you'll need to use e.g:
double m = sqrt((double) n);
The error you get simply means that the compiler cannot automatically select a sqrt function for you - the integer you pass needs to be converted to a floating point type, and the compiler doesn't know which floating point type and sqrt function it should select.

Related

How to get the int type matrix from the short matrix matrix product

We have two int8 matrices
A = B = [200, 200; 200, 200]. How can we get the int matrix product
C = A * B without converting A and B in advance.
Just use
C = A.cast<int>() * B.cast<int>();
If you want to make sure that no temporaries are generated (for casting A or B to int, try
C = A.cast<int>().lazyProduct(B.cast<int>());
For small (fixed-sized) matrices that is likely equivalent to the standard-product above. What is generated depends on your compiler (and optimization level and target machine).
If the code is performance critical, always benchmark and have a look at the generated assembly.

Sampling from all possible floats in D

In the D programming language, the standard random (std.random) module provides a simple mechanism for generating a random number in some specified range.
auto a = uniform(0, 1024, gen);
What is the best way in D to sample from all possible floating point values?
For clarification, sampling from all possible 32-bit integers can be done as follows:
auto l = uniform!int(); // randomly selected int from all possible integers
Depends on the kind of distribution you want.
A uniform distribution over all possible values could be done by generating a random ulong and then casting the bits into floating point. For T being float or double:
union both { ulong input; T output; }
both val;
val.input = uniform!"[]"(ulong.min, ulong.max);
return val.output;
Since roughly half of the positive floating point numbers are between 0 and 1, this method will often give you numbers near zero.`It will also give you infinity and NaN values.
Aside: This code should be fine with D, but would be undefined behavior in C/C++. Use memcpy there.
If you prefer a uniform distribution over all possible numbers in floating point (equal probability for 0..1 and 1..2 etc), you need something like the normal uniform!double, which unfortunately does not work very well for large numbers. It also will not generate infinity or NaN. You could generate double numbers and convert them to float, but I have no answer for generating random large double numbers.

What's the right way to compute integral base-2 logarithms at compile-time?

I have some positive constant value that comes from a different library than mine, call it the_val. Now, I want log_of_the_val to be floor(log_2(the_val)) - not speaking in C++ code - and I want that to happen at compile time, of course.
Now, with gcc, I could do something like
decltype(the_val) log_of_the_val = sizeof(the_val) * CHAR_BIT - __builtin_clz(the_val) - 1;
and that should work, I think (length - number of heading zeros). Otherwise, I could implement a constexpr function myself for it, but I'm betting that there's something else, and simpler, and portable, that I could use at compile-time. ... question is, what would that be?
The most straightforward solution is to use std::log2 from <cmath>, but that isn't specified to be constexpr - it is under gcc, but not under clang. (Actually, libstdc++ std::log2 calls __builtin_log2, which is constexpr under gcc.)
__builtin_clz is constexpr under both gcc and clang, so you may want to use that.
The fully portable solution is to write a recursive constexpr integral log2:
constexpr unsigned cilog2(unsigned val) { return val ? 1 + cilog2(val >> 1) : -1; }

multiple arithmetic expressions in processing

Ok, so still getting use to the basics with processing, and I am unsure if this is the correct way to do multiple arithmetic expressions with the same data, should I be typing each as its own code, or doing it like this?
here is the question;
Write the statements which perform the following arithmetic operations (note: the variable names can be changed). (i) a=50 b=60
c=43 result1 = a+b+c result2=a*b result3 = a/b
here is my code;
short a = 50;
short b = 60;
short c = 43;
int sum = a+b+c; // Subsection i
print (sum);
int sum2 = a*b; // Subsection ii
print (sum2);
int sum3 =a/b; // Subsection iii
print (sum3);
Using the same variable for a in all three expressions, like you're doing, is the right way. This means that if you wanted to change a, b, or c you'd only have to change it in one place.
You didn't mention what language, but there are a couple problems. It's hard to say what your knowledge level is, so I apologize in advance if this is beyond the scope of the assignment.
First, your variables are defined as short but they end up being assigned to int variables. That's implicit typecasting. Granted, short is basically a subset of int in most languages, but you should be aware that you're doing it and implicit typecasting can cause problems. It's slightly bad practice.
Second, your variable names are all called sumX but only one is a sum. That's definitely bad practice. Variable names should be meaningful and represent what they actually are.
Third, your division is dividing two integers and storing the result into an integer. This means that if you're using a strongly typed language you will be truncating the fractional portion of the quotient. You will get 0 as your output: 50 / 60 = 0.8333[...] which when converted to an integer truncates to 0. You may wish to consider using double or float as your data types if your answer is supposed to be accurate.

How to generate a seed from an xy coordinate

Iv'e been working on a perlin script but have been having problems with creating simple pseudo random values.
I need to be able to create a seed value from an xy coordinate but x+y has obvious problems with recurring values. Also they go into negative space so x^y doesn't work.
Sorry if this has been already answered somewhere else but either I didn't understand or couldn't find it.
Do you want to assing a repetible random number to each x,y pair ?
Using a linear or in general function combination of the x,y as a seed will give artifacts in the distribution (at least if you don't use a very complex function).
Try with this, I've the same problem ant it worked for me
//seeded random for JS - integer
function irnd2()
{
a=1664525;
c=1013904223;
m=4294967296;
rnd2.r=(rnd2.r*a+c)%m;
return rnd2.r;
}
//seeded random for JS - double [0,1]
function rnd2()
{
a=1664525;
c=1013904223;
m=4294967296;
rnd2.r=(rnd2.r*a+c)%m;
return rnd2.r/m;
}
rnd2.r=192837463;
//seed function
function seed2(s)
{
s=s>0?s:-s;
rnd2.r=192837463^s;
}
//my smart seed from 2 integer
function myseed(x,y)
{
seed2(x);//x is integer
var sx=irnd2();//sx is integer
seed2(y);//y is integer
var sy=irnd2();//sy is integer
seed2(sx^sy);//using binary xor you won't lose information
}
In order to use it :
myseed(x,y);
irnd2();
In this manner you can obtain a good uncorrelated random sequence.
I use it in JS but it should work also in other languages supposing the argument of seed and the returned value of rnd is an integer.
You need to better define the problem to get an optimal answer.
If your x and y values are relatively small, you could place them into the high and low portions of an integer (is the seed in your language an integer), e.g. for a 32-bit platform:
int seed = x << 16 + y;
If the seed value is not allowed to be negative (I didn't fully understand what you meant by "negative space" in your question, whether you were referring to geography or the seed value), you can take the absolute value of the seed.
If you meant that the coordinates can have negative values, your best course of action depends on whether you want the same seed for a coordinate and for it's inverse.
Take the absolute value of both x and y first; then x^y will work fine. One of the easiest ways to create a pseudo-random source is with time. You might try multiplying x^y by the current system time; this method has an extremely low chance of generating recurring seed values.
If you know the range of values you have, you could simply cast x and y as strings padded with zeroes, append the two strings, then run the resulting string through a hash function.
In C#, adapted and improved from alexroat's answer. Just set Random.seed = MyUtils.GetSeedXY(x, y) and you're good to go.
public static class MyUtils
{
static int seed2(int _s)
{
var s = 192837463 ^ System.Math.Abs(_s);
var a = 1664525;
var c = 1013904223;
var m = 4294967296;
return (int) ((s * a + c) % m);
}
public static int GetSeedXY(int x, int y)
{
int sx = seed2(x * 1947);
int sy = seed2(y * 2904);
return seed2(sx ^ sy);
}
}

Resources