Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect result when variable self assignment is used #32

Closed
cpizzolato opened this issue Jun 18, 2019 · 3 comments
Closed

Incorrect result when variable self assignment is used #32

cpizzolato opened this issue Jun 18, 2019 · 3 comments

Comments

@cpizzolato
Copy link

I have noticed the following behaviour when assigning the result of an operation to a variable used in the operation itself:

#include <autodiff/forward.hpp>

int main() {

	using DoubleT = dual;
	DoubleT a = 1;
	a = a - 2*a;
	cout << "it's " << a << " should be -1\n"; // dual returns -4

	a = 1;
	a = a + 2 * a;
	cout << "it's " << a << " should be 3\n";  // dual returns 4

	a = 1;
	a = a - a;
	cout << "it's " << a << " should be 0\n";  // dual returns -2

	a = 1;
	a = a + a;
	cout << "it's " << a << " should be 2\n"; // dual returns 2

	a = 1;
	a = 2*a - a;
	cout << "it's " << a << " should be 1\n";  // dual returns -3

	a = 1;
	a = 2*a + a;
	cout << "it's " << a << " should be 3\n";  // dual returns 3

	a = 1;
	a = DoubleT{ 2 * a - a };
	cout << "it's " << a << " should be 1\n";  // dual correctly returns 1
}
@allanleal
Copy link
Member

allanleal commented Jun 18, 2019

There is some aliasing happening there. dual is assuming by default that there is no aliasing (that is, it is not used on the right-hand side). In Eigen, one needs to explicitly state that there is no alias so that a temporary is not created. If we follow Eigen's convention, then we would need to write:

a.noalias() = 2*x - y; // a is not used on the right-hand side and thus we can avoid a temporary
a = 2*x - y; // this also works, but a temporary is created to hold 2*x - y before assigning to a
a = 2*a - a; // a is used on the right-hand side, but now a temporary holding the result prevents a from changing in the middle of the evaluation.

@allanleal
Copy link
Member

Just submitted a pull request with the fix. It should be merged to the master branch soon.

allanleal added a commit that referenced this issue Jun 18, 2019
* Fix autodiff header figure for changes in v0.5.0

* Fix issue 32 - preventing aliasing

* Increment version to 0.5.1
@allanleal
Copy link
Member

I'll close this issue now that a bug fix has been implemented. Thanks a lot for reporting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants