How to pass an expression as an argument/parameter? - c++

Say I have a polynomial function f(x), and I want to use this expression into either the expression g(x) or h(x), depending on which the user chooses. Is this possible?
for example
int main() {
float fexpression = /* polynomial function f(x) here */;
/* some code where user picks g(x) or h(x) */
if (/* gexpression == true */)
cout << gfunction(fexpression);
else /* h expression == true */
cout << hfunction(fexpression);
return 0;
}
float gfunction(float j){
float var = /* some function representing g(f(x)) == g(j) */;
return var;
}
float hfunction(float j){
float var = /* some function representing h(f(x)) == h(j) */;
return var;
}
it just doesnt seem right to me that I can pass a variable that is an expression, such as
float fexpression = ....

You want a function pointer.
Make the expression a function.
float fexpression( float x )
{
return (5*(pow(x,4))) + (3*(pow(x, 3))) + (10 * x) - 5
}
This code, as you wrote it, will then pass the functionality itself.
if (/* gexpression == true */)
cout << gfunction(fexpression);
else /* h expression == true */
cout << hfunction(fexpression);

I tried to explain details of this in the comment section of Drew's answer, but it got lost in the formatting... so had to start another answer.
#DrewDorman's is right in saying you need to just define your expression as a function:
float fexpression( float x )
{
return (5*(pow(x,4))) + (3*(pow(x, 3))) + (10 * x) - 5
}
What is missing (for you) is the following (which you would get from reading Drew's link...):
define your gfunction as follows (for instance)
float gfunction(float (*funcp)(float)) {
// lots of stuff to determine the value of x
return (*funcp)(x);
}
This is how gfunction can evaluate your polynomial. Do something similar for hfunction
When you call gfunction, you have to reference fexpression as follows:
cout << gfunction(&fexpression);
the & matters... it was also missing from Drew's answer.

Related

when need to do this in c++; if(x = 0) {}

I noticed sometimes developers do these in their project;
while(int x = 0) {//run code}
int y = 0;
if (y = someFunction())
{//run code}
I want ask;
why c++ allow to do these in loops like while,(maybe for as well?) and if-else statements, what is the usage?
when someone should do this in his project?
and when conditions like these give result true?
what is the usage?
Declaration inside if/for/while allows to reduce scope of the variable.
so, instead of
int y = somevalue();
if (y) {// y != 0
// ...
}
// y still usable :/
or
{ // extra block :/
int y = somevalue();
if (y) {// y != 0
// ...
}
}
// y no longer usable :)
you might directly do:
if (int y = somevalue()) // y != 0
// ...
}
// y no longer usable :)
with syntax which might indeed surprise.
For more controversial:
int y;
// ...
if (y = somevalue()) // y != 0
// ...
}
// y still usable :)
it is allowed as that assignation is an expression convertible to bool (value of y = x is y (which has been assigned to x)).
it is more controversial as error prone as unclear if = or == is expected.
some convention use extra parents to more clearly express assignation
if ((y = somevalue())) // really = intended, not ==
// ...
}
when someone should do this in his project?
For existing projects, try to use existing convention.
For new project, you have to do the trade of:
scope versus syntax not shared with other language which might be surprising
and when conditions like these give result true?
when given expression convert to true, so non zero integral, non null pointer.
c++17 introduces another syntax to allow to split declaration and condition for if/while. (for already allow that split)
if (int y = somevalue(); y != 42) // y != 42
// ...
}
// y no longer usable :)

C++ Return a Variable of an object

I am learning c++ currently and i have run to this problem:
Error Message: This Code should be of type bool or should be converted to bool.
The main function must stay the same, so i was wondering, that i use the line [A] and actuall return an bool.
The method should compare two cubics with each other, if they are the same or not the same.
Thanks in advance! :) <3
#include <iostream>
#include <cfloat>
class cubics
{
private:
double x,y,z;
bool var;
public:
cubics same(cubics cube)
{
double difference_x = x - cube.x;
double difference_y = y - cube.y;
double difference_z = z - cube.z;
if ( // If the difference between two objects are 0, then both cubics are the same; epsilon is used because we calculate with double floating precision to avoid the error)
(difference_x <= std::numeric_limits<double>::epsilon( )) and
(difference_y <= std::numeric_limits<double>::epsilon( )) and
(difference_z <= std::numeric_limits<double>::epsilon( ))
)
{
return (cube.var= true); // [A] I'm actually returning bool. But does the compiler want me to return the whole object!?
}
else
{
return (cube.var=false); // [A]
}
}
int main(){
cubics q2,q3;
cout << "The Cubics q2 and q3 are ";
if (q2.same(q3)) // <-- This line confuses me, however it must stay formally for my computerproject the same :) I understand that it means q2.same(q3) == true, but i don't know how i can return a boolean. I tryed [A]
cout << "same." << endl;
else
cout << "not same." << endl;
}
}
To return a boolean, you make the function… return a boolean.
Right now, it is trying to return an object of type cubics:
cubics same(cubics cube)
^^^^^^
Instead:
bool same(cubics cube)
^^^^
And return true, or return false, as appropriate.
That's it!
Your bool var doesn't need to exist at all.
I'd also recommend you take cube by reference; there's no need to take it by value, which makes a copy. So:
bool same(const cubics& cube)

use of 'n' before deduction of 'auto' C++

I'm trying to have my function return 3 values (n, down and across) I've read online how 'auto' can be used but must be doing something wrong.
The function takes in a 2D vector of integers (as well as other variables) and checks for how many numbers are connected to board[0][0] such that they are the same number.
I've tried putting auto in front of the function inside the function itself, tried leaving it blank, tried just having chain = chainNodes(...) but I always seem to get an error. Here's the code:
tuple<int, int, int> chainNodes(vector<vector<int>> board, int originalNum,
unsigned int across, unsigned int down, int ijSum,
int n)
{
struct chain {
int n, down, across;
};
if(down + across > ijSum) {
ijSum = down + across;
} else if((down + across == ijSum) &&
((down - across) * (down - across) < (ijSum) * (ijSum))) {
ijSum = down + across;
}
board[down][across] = 0;
n += 1;
// Check below
if((down != (board.size() - 1)) && (board[down + 1][across]) == originalNum) {
down += 1;
auto [n, iPoint, jPoint] = chainNodes(board, originalNum, across, down, ijSum, n);
down -= 1;
}
// Check right, up and left (I've removed so its not too messy here)
return chain{n, down, across};
}
Sorry, I forgot to include the error message.
error: use of 'n' before deduction of 'auto'
It occurs on the line that uses auto.
Issue with
auto [n, iPoint, jPoint] = chainNodes(board, originalNum, across, down, ijSum, n);
is similar to
auto n = foo(n); // `foo(n)` uses `n` from `auto n`,
// not the one from outer scope as function parameter
The construct int a = a + 1; is legal but lead to UB as reading uninitialized variable.
That kind of construct allows legal and valid behavior void* p = &p;.
Your code has other errors and it is not clear for me expected behavior of the function.
So not sure if following is the correct fix, but you might want:
n = std::get<0>(chainNodes(board, originalNum, across, down, ijSum, n));

Mantain the original value in a recursive function c++

I am trying to solve a square root in a recursive way. I do not want the code to solve that! I am almost done, but I do not know how to mantain the original value of the function:
float raizCuadrada(float num, float err) {
float nuevo = num / 2;
float resta=(nuevo*nuevo)-num;
if(resta>err){
return (raizCuadrada(nuevo, err));
}
else if (resta <= err) {
return (nuevo);
}
}
I basicly want to know how to "save" that first "num" call, somewhere, to use it ALWAYS in the "resta", the "- num" should be always the number that 1st put.
NOTES: I cannot input more inputs. I can only input 1 number and the error.
You can define a global variable at the top of your code.
float num_fixed;
float raizCuadrada(float num, float err) {
float nuevo = num / 2;
float resta=(nuevo*nuevo)-num_fixed;
if(resta>err){
return (raizCuadrada(nuevo, err));
}
else {
return (nuevo);
}
}
int main(void){
float num = 2.0;
float err = 0.000001;
float output;
num_fixed = num;
output = raizCuadrada(num, err);
}
I would recommend the two solutions that have been proposed. Either overload a function that takes three arguments or use a global.
If you for some reason don't want to do that, you can use some trickery:
float raizCuadrada(float num, float err) {
static float org = -1;
if(org<0)
org = num;
float nuevo = num / 2;
float resta=(nuevo*nuevo)-org;
float ret;
if(resta>err)
ret = raizCuadrada(nuevo, err);
else
ret = nuevo;
if(org>=0)
org=-1;
return ret;
}
I would not recommend this method unless you really have a special need for it. It is quite easy to do mistakes, and I cannot think of any real benefit. But since it is possible, I wanted to show it.
I basicly want to know how to "save" that first "num" call, somewhere,
to use it ALWAYS in the "resta", the "- num" should be always the
number that 1st put.
NOTES: I cannot input more inputs. I can only input 1 number and the
error. c++
The solution I most often use is to separate the two 'efforts' into two methods:
1) Start with a method (use your original method name) to save the first variable to a safe space. I will leave the 'where' up to you. Here I have simply made up a new variable name (origNum), in a scope available to the code of each method. In C++, I would expect that the class containing these methods would 'save' and use an instance data attribute.
float raizCuadrada(float num, float err) // same name as original
{
origNum = num; // "save" original 'num'
return (raizCuadrada2(num, err)); // continue normally
}
2) Then a mild re-factor of your previous code uses the "saved" value. Since you can not change the parameters, I suggest a slight method name change, here I created raizCuadrada with suffix '2'.
float raizCuadrada2(float num, float err) {
float nuevo = num / 2;
float resta=(nuevo*nuevo)-origNum; // use origNum here
if(resta>err){
return (raizCuadrada(nuevo, err));
}
else if (resta <= err) {
return (nuevo);
}
}
note - not compiled. not tested.

implementation of isnan() function

I am a beginner to c++ programming and I am given a task of implementation of fixed point math arithmetic in c++. here I am trying to implementation a function isnan() which returns true if the number is not-a-number else will return false.
Test file
#include "fixed_point_header.h"
int main()
{
fp::fixed_point<long long int, 63> a=fp::fixed_point<long long int, 63>::positive_infinity(); // will assign positive infinity value to a from an function from header
fp::fixed_point<long long int, 63> b=fp::fixed_point<long long int, 63>::negative_infinity(); // will assign positive infinity value to b from an function from header
float nan=fp::fixed_point<long long int, 63>::isnan(a,b);
printf( "fixed point nan value == %f\n", float (nan));
}
In the header I want to do somewhat like the code shown below if positive and negative infinity values are added, the isnan function should return 1 else 0.
Header file
#include fixed_point_header
static fp::fixed_point<FP, I, F> isnan (fp::fixed_point<FP, I, F> x,fp::fixed_point<FP, I, F> y){
/*if ( x + y ) happens, ie. x and y are infinities
{
should return 1; }
else {
should return 0; }
} */
can anyone please tell how to proceed with it? or how to solve this paradigm
I am trying to implementation a function isnan() which returns true if the number is not-a-number else will return false.
That's simple enough; define a reserved value to represent nan (as you have for the infinities), and compare with that:
bool isnan(fixed_point x) {
return x == fixed_point::nan();
}
I want to do somewhat like the code shown below if positive and negative infinity values are added, the isnan function should return 1 else 0
It would be the responsibility of the addition operator to check the inputs and return nan if appropriate:
fixed_point operator+(fixed_point x, fixed_point y) {
if (x == fixed_point::nan() || y == fixed_point::nan()) {
return nan;
}
if (x == fixed_point::positive_infinity()) {
return y == fixed_point::negative_infinity() ? fixed_point::nan() : x;
}
// and so on
}
then the test in main becomes:
bool nan = fixed_point::isnan(a+b);