Related
I have a very simple question by I am very confused by the way I could implement this. I want to create a Boolean variable in a single line composed of ternary statement such as this:
boolean = a ? b : (c ? d : (e ? f : (g ? i : j );
It is working for 1, 2 or 3 such imbricate conditions for the purposes of my codes but I which to write it in a way that I could choose how many such ternary conditions I want to put into each other to define the Boolean variable.
And I am stuck with this because at the end it looks like I cannot add the last condition. I have tried to think of a recursive function, maybe with some counter, but I could not manage to write it. I do not know if what I ask is simpler or clear.
The condition are not fully independent of each other, there are intervals (coordinates in space) that follow each other somehow. So for example the 'a' in my example would be something like 11 and then it would continue when it is false with a new condition saying 22 and so on. Hence my idea of introducing some counter to put into the conditions.
But when I arrive at the last false condition, I don't know what to do because I cannot set up a random z>something to make my code work.
I am trying something like:
bool f(double x, double value, double z, double d, double n, double step, int &count);{
bool result;
count++;
if (count == n) {return result}
result = (x >=value+count*step && x<value+(count+1)*step) ? z>=d : f(x,value,z,d,n,step, &count);
}
So of course, besides probably many mistakes in the way I am writing recursive function since I never use them and do not use C or C++ usually, it will appear that in the last call of the function by itself, we will have something like a ? b : without the last parameter if the statement is false.
I tried to be as clear as I could. You can ask questions if you do not get the point. And any help is welcome, recursive functions, normal functions or a way to do it with no function at all...
Best regards and thanks in advance for your answers!
Edit:
The code with if should be something like:
if (a){
b}
else{
if (c){
d}
else{
if(e){
f}
else{
if(g){
I}
else{
j}
I may have forgotten some bracket but I hope it is understandable. And this point is to continue with, say n, if statements like this in a single line to create a Boolean variable and then being able to choose n instead of rewriting a new code each time I want to add an if statement.
EDIT about recursion:
Can someone explains me why this kind of function creates an infinite loop?
bool f(double x, double l, double z, double d, double step, int &count){
int n = (int)l/step;\\number of steps
count++;
if (count < n)
return (x >=l+count*step && x<l+(count+1)*step) ? z>=d*count : f(x,l,z,d,step,count);
else
return z>=d*(count-1);
}
I set the counter 'count' to -1 before calling the function and it seems to be the problem. It does the loop correctly but then it restarts again and again so that I cannot even check if my code makes any sense for my purpose. I thought after each return calling the function recursively, it would increase the counter but once it reaches n, it should return something else and go out of the function, not restart the counter and doing everything again...
To write that if ... else if ladder more clearly, get rid of the brackets and get rid of the indentation. Like this:
if (a)
boolean = b;
else if (c)
boolean = d;
and so on. But I’d be inclined to write it as a function:
if (a)
return b;
else if (c)
return d;
and so on. Still, if you like the ternary operator, it can be written in a disciplined way that is easily read:
boolean = a ? b
: c ? d
: e ? f
: g;
[4th version of the answer, taking into account comments]
In the particular case of the first simple example provided, it is possible to write a variadic function. Here the template ...args parameter indicates a variable number of parameters. One can call f(false,false,true) or f(false,false,false,true,true) or more parameters.
bool ff(bool a, bool b, bool c) {
return a ? b : c;
}
template<class ...Args>
bool ff(bool a, bool b, Args ...args){
return a ? b : ff(args...);
}
As user463035818 mentioned, there is a risk of short-circuiting in this first call of ff(.) function (by main), when all booleans are likely to be evaluated during this fist call. I don't know what would really happen with optimization by the compiler, with possible inlining and unrolling, but it is useless to stress the compiler.
Anyway I now understand that the number of steps is an input parameter, and a variadic template function does not seem to be applicable. It is certainly possible to solve it with a recursive function, similar to the one you proposed. However, in my opinion, a simple 'for loop' will be both efficient and flexible.
In my previous answer, I proposed a solution based on a for loop. However, as it does not correspond to your needs, because I misunderstood the mathematical problem, I removed it.
Instead, I come back to the second recursive function that you proposed in your post. You asked why the recursion did not finish. I could not comment it directly because of my poor reputation. As I did not see why the programme did not stop, I implemented it and the programme finished normally, but with a result that does not seem correct. I see a problem about parameter l. It seems to correspond both to a range for x and to a minimal value for x. I tried to correct it. It may happen that I did not select the input parameter values correctly . Therefore, I put the corresponding program hereafter for you to be able to check it.
#include <iostream>
bool f(double x, double xmin, double range, double z, double d, double step, int &count){
int n = range/step; //number of steps
count++;
if (count < n) {
double a = xmin + count*step;
return ((x >=a) && (x< a + step)) ? z>=d*count : f(x,xmin,range,z,d,step,count);
} else
return z>=d*(count-1);
}
int main () {
int count = -1;
double xmin = 0.0;
double x = 2.0;
double range = 4.0;
double step = 1.0;
double d = 1.0;
double z = 2.0;
bool test = f (x, xmin, range, z, d, step, count);
std::cout << "test = " << test << "\n";
std::cout << "count = " << count << "\n";
return 0;
}
In this particular case, it would be better to replace range by n as input parameter, to avoid redundant calculation of n.
Readability vs efficiency
The point is I don't want my code to be elegant or readable but efficient.
Honestly, I think this is not a good strategy. Inefficient code is not elegant. This does of course not imply that readable code is automatically efficient.
However, it is much easier to accidentally prevent the compiler doing an optimization rather than pushing it to emit better code than it already does anyhow. Readable code does contain less errors and helps you to avoid obvious inefficiencies. That being said,...
Why not to write a variadic conditional function?
Besides readability there is one more thing to consider: short-circuiting. With the plain conditional
bool x = condition ? t : some_other_function_call();
in case condition is true, then some_other_function_call() will not be evaluated, while in
bool x = foo(t,some_other_function_call());
the other function will be called in either case. You cannot get short-circuiting with foo.
What to do instead?
The answer by Pete Becker nicely demonstrates how to write the conditions in a clean way (most importantly you don't need to nest the cases when they are mutually exclusive (they are for the ternary!)).
Anyhow... how could a variadic conditional function be written?
Just for the sake of completeness, this is how you could write such a function to replace bool x = a ? b : (c ? d : (e ? f : (g ? i : j ); with a funciton call (please dont):
// DISCLAIMER: DONT DO THIS
bool my_conditional(std::vector<bool> x){
if (x.size() == 1) return *x.begin();
bool condition = *x.begin();
bool true_value = *(x.begin()+1);
return condition ? true_value : my_ternary({x.begin()+2,x.end()});
}
You could call it like this:
my_conditional({ condition1, true_value1, condition2, true_value2, false_value});
eg
std::cout << my_conditional({false,false,false,false,false});
prints 0.
The question might be unclear, what I'm asking and searching for is this: in C++ programming one introduces the type of the variabile with commands
int, for integer
bool, for boolean
double
float
and so on..
I wondered if there is a similar way to define the "prime" like
prime n;
so then when he program will recall $n$, it automatically will take only prime numbers.
An application of that with a simple program: supposing I want to create a list of the integer part of the operation
π^n
where π = Pi and n = prime number.
Mathematically it would be
Floor[π^n]
No, I now how to write a program to list some prime numbers, for example:
int main ()
{
for (int i=2; i<100; i++)
{
bool prime=true;
for (int j=2; j*j<=i; j++)
{
if (i % j == 0)
{
prime=false;
break;
}
}
if(prime) cout << i << " ";
}
return 0;
}
But I am not really sure of how to continue.. Also I'm sorry for my bad way to express what I would like to do!
The Answer regarding all mentioned language tags is No.
Primes are included in int since all primes are integer numbers.
Finding whether an integer number is also prime requires an algorithm implemented in a function.
Suppose that prime type exists and you initialize it with a vulue of 4 which isn't prime...the compiler should say something like a type mismatch and not allow you to run the program.
sounds pretty simple so far but what happens when there's a really big number. it has to apply an algorithm which means it's no longer a compiler problem.
There are some specialised languages and libraries. For example Pari/Gp which has a nice interpreter with many prime related functions (the interpreter calls into a C-library, so its fast): For examples
primes(100)
gives you the vector of the first 100 primes. There is even a primality test with isprime. It is really nice and easy to start playing around with. When you interested in heavy algebraic number theory stuff, that is possible too. Your example:
P = precision(Pi, 1000)
vector(100, i, floor((P^prime(i))))
The first line create PI with a high enough precision for exponentiation, the second line creates a list with the evaluation of floor(Pi^p) with p ranging over ther first 100 primes.
There is a program gp2c which translates your high level gp interpreter scripts into compileable C-Programs using the underlying library. You can use that when you need more speed, but for a start: use the gp Interpreter.
There are other packages as well, I would also recommend SAGE. It is an Open Source alternative to Maple and Mathematica. SAGE uses Python as its scripting language, here you would use:
for p in primes_first_n(100): print p
[ floor( pi^p ) for p in primes_first_n(100) ]
You can try it out by creating an account for the online version of SAGE
No my friend, there is not any option like whatever you ask.
But there is some way for that:
First, use Structure, Union, Typedef these are used to create data type in c lang
or else, Second, create a function prime() and add to library, and whenever you want include that header file and then use that fxn
Add User-Define function to library (using tlib.exe-TurboLibrarian):-
Info:-in cmd- tlib math.lib + c:\prime.obj (NOTE: use '-' to delete fxn from library)
How to use:
#include< math.h>
........................
........................
prime(n) blah blah blah
........................
By this way you can check prime no very quickly and add those to array, then you will have an array containing only prime no(same as datatype accepting prime no)
COOL NO?
I have the following expression:
A = cos(5x),
where x is a letter indicating a generic parameter.
In my program I have to work on A, and after some calculations I must have a result that must still be a function of x , explicitly.
In order to do that, what kind of variable should A (and I guess all the other variables that I use for my calculations) be?
Many thanks to whom will answer
I'm guessing you need precision. In which case, double is probably what you want.
You can also use float if you need to operate on a lot of floating-point numbers (think in the order of thousands or more) and analysis of the algorithm has shown that the reduced range and accuracy don't pose a problem.
If you need more range or accuracy than double, long double can also be used.
To define function A(x) = cos(5 * x)
You may do:
Regular function:
double A(double x) { return std::cos(5 * x); }
Lambda:
auto A = [](double x) { return std::cos(5 * x); };
And then just call it as any callable object.
A(4.); // cos(20.)
It sounds like you're trying to do a symbolic calculation, ie
A = magic(cos(5 x))
B = acos(A)
print B
> 5 x
If so, there isn't a simple datatype that will do this for you, unless you're programming in Mathematica.
The most general answer is "A will be an Expression in some AST representation for which you have a general algebraic solver."
However, if you really want to end up with a C++ function you can call (instead of a symbolic representation you can print as well as evaluating), you can just use function composition. In that case, A would be a
std::function<double (double )>
or something similar.
1) I want to pass a the pointer of a QVector to a function and then do things with it. I tried this:
void MainWindow::createLinearVector(QVector<float> *vector, float min, float max )
{
float elementDiff=(max-min)/(vector->size()-1);
if(max>min) min -= elementDiff;
else min += elementDiff;
for(int i=0; i< vector->size()+1 ; i++ )
{
min += elementDiff;
*(vector+i) = min; //Problematic line
}
}
However the compiler gives me "no match for operator =" for the *(vector+i) = min; line. What could be the best way to perform actions like this on a QVector?
2) The function is supposed to linearly distribute values on the vector for a plot, in a way the matlab : operator works, for instance vector(a:b:c). What is the simpliest and best way to perform such things in Qt?
EDIT:
With help from here the initial problem is solved. :)
I also improved the metod in itself. The precision could be improved a lot by using linear interpolation instead of multiple additions like above. With multiple addition an error is accumulating, which is eliminated in large part by linear interpolation.
Btw, the if statement in the first function was unecessary and possible to remove by just rearranging stuff a little bit even in the multiple addition method.
void MainWindow::createLinearVector(QVector<double> &vector, double min, double max )
{
double range = max-min;
double n = vector.size();
vector[0]=min;
for(int i=1; i< n ; i++ )
{
vector[i] = min+ i/(n-1)*range;
}
}
I considered using some enchanced loop for this, but would it be more practical?
With for instance a foreach loop I would still have to increment some variable for the interpolation right? And also make a conditional for skipping the first element?
I want to place a float a certain place in the QVector.
Then use this:
(*vector)[i] = min; //Problematic line
A vector is a pointer to a QVector, *vector will be a QVector, which can be indiced with [i] like any QVector. However, due to precedence, one needs parentheses to get the order of operations right.
I think, first u need use the Mutable iterator for this stuff: Qt doc link
Something like this:
QMutableVectorIterator<float> i(vector);
i.toBack();
while (i.hasPrevious())
qDebug() << i.{your code}
Right, so it does not make much sense to use a QVector pointer in here. These are the reasons for that:
Using a reference for the method parameter should be more C++'ish if the implicit sharing is not fast enough for you.
Although, most of the cases you would not even need a reference when just passing arguments around without getting the result back in the same argument (i.e. output argument). That is because *QVector is implicitly shared and the copy only happens for the write as per documentation. Luckily, the syntax will be the same for the calling and internal implementation of the method in both cases, so it is easy to change from one to another.
Using smart pointers is preferable instead of raw pointers, but here both are unnecessarily complex solutions in my opinion.
So, I would suggest to refactor your code into this:
void MainWindow::createLinearVector(QVector<float> &vector, float min, float max)
{
float elementDiff = (max-min) / (vector.size()-1);
min += ((max>min) ? (-elementDiff) : elementDiff)
foreach (float f, vector) {
min += elementDiff;
f = min;
}
}
Note that I fixed up the following things in your code:
Reference type parameter as opposed to pointer
"->" member resolution to "." respectively
Ternary operation instead of the unnatural if/else in this case
Qt's foreach instead of low-level indexing in which case your original point becomes moot
This is then how you would invoke the method from the caller:
createLinearVector(vector, fmin, fmax);
I've just finished second year at Uni doing a games course, this is always been bugging me how math and game programming are related. Up until now I've been using Vectors, Matrices, and Quaternions in games, I can under stand how these fit into games.
This is a General Question about the relationship between Maths and Programming for Real Time Graphics, I'm curious on how dynamic the maths is. Is it a case where all the formulas and derivatives are predefined(semi defined)?
Is it even feasible to calculate derivatives/integrals in realtime?
These are some of things I don't see how they fit inside programming/maths As an example.
MacLaurin/Talor Series I can see this is useful, but is it the case that you must pass your function and its derivatives, or can you pass it a single function and have it work out the derivatives for you?
MacLaurin(sin(X)); or MacLaurin(sin(x), cos(x), -sin(x));
Derivatives /Integrals This is related to the first point. Calculating the y' of a function done dynamically at run time or is this something that is statically done perhaps with variables inside a set function.
f = derive(x); or f = derivedX;
Bilnear Patches We learned this as a way to possible generate landscapes in small chunks that could be 'sewen' together, is this something that happens in games? I've never heard of this (granted my knowlages is very limited) being used with procedural methods or otherwise. What I've done so far involves arrays for vertex information being processesed.
Sorry if this is off topic, but the community here seems spot on, on this kinda thing.
Thanks.
Skizz's answer is true when taken literally, but only a small change is required to make it possible to compute the derivative of a C++ function. We modify skizz's function f to
template<class Float> f (Float x)
{
return x * x + Float(4.0f) * x + Float(6.0f); // f(x) = x^2 + 4x + 6
}
It is now possible to write a C++ function to compute the derivative of f with respect to x. Here is a complete self-contained program to compute the derivative of f. It is exact (to machine precision) as it's not using an inaccurate method like finite differences. I explain how it works in a paper I wrote. It generalises to higher derivatives. Note that much of the work is done statically by the compiler. If you turn up optimization, and your compiler inlines decently, it should be as fast as anything you could write by hand for simple functions. (Sometimes faster! In particular, it's quite good at amortising the cost of computing f and f' simultaneously because it makes common subexpression elimination easier for the compiler to spot than if you write separate functions for f and f'.)
using namespace std;
template<class Float>
Float f(Float x)
{
return x * x + Float(4.0f) * x + Float(6.0f);
}
struct D
{
D(float x0, float dx0 = 0) : x(x0), dx(dx0) { }
float x, dx;
};
D operator+(const D &a, const D &b)
{
// The rule for the sum of two functions.
return D(a.x+b.x, a.dx+b.dx);
}
D operator*(const D &a, const D &b)
{
// The usual Leibniz product rule.
return D(a.x*b.x, a.x*b.dx+a.dx*b.x);
}
// Here's the function skizz said you couldn't write.
float d(D (*f)(D), float x) {
return f(D(x, 1.0f)).dx;
}
int main()
{
cout << f(0) << endl;
// We can't just take the address of f. We need to say which instance of the
// template we need. In this case, f<D>.
cout << d(&f<D>, 0.0f) << endl;
}
It prints the results 6 and 4 as you should expect. Try other functions f. A nice exercise is to try working out the rules to allow subtraction, division, trig functions etc.
2) Derivatives and integrals are usually not computed on large data sets in real time, its too expensive. Instead they are precomputed. For example (at the top of my head) to render a single scatter media Bo Sun et al. use their "airlight model" which consists of a lot of algebraic shortcuts to get a precomputed lookup table.
3) Streaming large data sets is a big topic, especially in terrain.
A lot of the maths you will encounter in games is to solve very specific problems, and is usually kept simple. Linear algebra is used far more than any calculus. In Graphics (I like this the most) a lot of the algorithms come from research done in academia, and then they are modified for speed by game programmers: although even academic research makes speed their goal these days.
I recommend the two books Real time collision detection and Real time rendering, which contain the guts of most of the maths and concepts used in game engine programming.
I think there's a fundamental problem with your understanding of the C++ language itself. Functions in C++ are not the same as mathmatical functions. So, in C++, you could define a function (which I will now call methods to avoid confusion) to implement a mathmatical function:
float f (float x)
{
return x * x + 4.0f * x + 6.0f; // f(x) = x^2 + 4x + 6
}
In C++, there is no way to do anything with the method f other than to get the value of f(x) for a given x. The mathmatical function f(x) can be transformed quite easily, f'(x) for example, which in the example above is f'(x) = 2x + 4. To do this in C++ you'd need to define a method df (x):
float df (float x)
{
return 2.0f * x + 4.0f; // f'(x) = 2x + 4
}
you can't do this:
get_derivative (f(x));
and have the method get_derivative transform the method f(x) for you.
Also, you would have to ensure that when you wanted the derivative of f that you call the method df. If you called the method for the derivative of g by accident, your results would be wrong.
We can, however, approximate the derivative of f(x) for a given x:
float d (float (*f) (float x), x) // pass a pointer to the method f and the value x
{
const float epsilon = a small value;
float dy = f(x+epsilon/2.0f) - f(x-epsilon/2.0f);
return epsilon / dy;
}
but this is very unstable and quite inaccurate.
Now, in C++ you can create a class to help here:
class Function
{
public:
virtual float f (float x) = 0; // f(x)
virtual float df (float x) = 0; // f'(x)
virtual float ddf (float x) = 0; // f''(x)
// if you wanted further transformations you'd need to add methods for them
};
and create our specific mathmatical function:
class ExampleFunction : Function
{
float f (float x) { return x * x + 4.0f * x + 6.0f; } // f(x) = x^2 + 4x + 6
float df (float x) { return 2.0f * x + 4.0f; } // f'(x) = 2x + 4
float ddf (float x) { return 2.0f; } // f''(x) = 2
};
and pass an instance of this class to a series expansion routine:
float Series (Function &f, float x)
{
return f.f (x) + f.df (x) + f.ddf (x); // series = f(x) + f'(x) + f''(x)
}
but, we're still having to create a method for the function's derivative ourselves, but at least we're not going to accidentally call the wrong one.
Now, as others have stated, games tend to favour speed, so a lot of the maths is simplified: interpolation, pre-computed tables, etc.
Most of the maths in games is designed to to as cheap to calculate as possible, trading speed over accuracy. For example, much of the number crunching uses integers or single-precision floats rather than doubles.
Not sure about your specific examples, but if you can define a cheap (to calculate) formula for a derivative beforehand, then that is preferable to calculating things on the fly.
In games, performance is paramount. You won't find anything that's done dynamically when it could be done statically, unless it leads to a notable increase in visual fidelity.
You might be interested in compile time symbolic differentiation. This can (in principle) be done with c++ templates. No idea as to whether games do this in practice (symbolic differentiation might be too expensive to program right and such extensive template use might be too expensive in compile time, I have no idea).
However, I thought that you might find the discussion of this topic interesting. Googling "c++ template symbolic derivative" gives a few articles.
There's many great answers if you are interested in symbolic calculation and computation of derivatives.
However, just as a sanity check, this kind of symbolic (analytical) calculus isn't practical to do at real time in the context of games.
In my experience (which is more 3D geometry in computer vision than games), most of the calculus and math in 3D geometry comes in by way of computing things offline ahead of time and then coding to implement this math. It's very seldom that you'll need to symbolically compute things on the fly and then get on-the-fly analytical formulae this way.
Can any game programmers verify?
1), 2)
MacLaurin/Taylor series (1) are constructed from derivatives (2) in any case.
Yes, you are unlikely to need to symbolically compute any of these at run-time - but for sure user207442's answer is great if you need it.
What you do find is that you need to perform a mathematical calculation and that you need to do it in reasonable time, or sometimes very fast. To do this, even if you re-use other's solutions, you will need to understand basic analysis.
If you do have to solve the problem yourself, the upside is that you often only need an approximate answer. This means that, for example, a series type expansion may well allow you to reduce a complex function to a simple linear or quadratic, which will be very fast.
For integrals, the you can often compute the result numerically, but it will always be much slower than an analytic solution. The difference may well be the difference between being practical or not.
In short: Yes, you need to learn the maths, but in order to write the program rather than have the program do it for you.