I'm attempting to make a class that holds a (in theory) infinite amount of digits using c-strings, since ints have a limit. I am having a lot of trouble with multiplication and have begun to confuse myself. I am a student, so any help and mistakes I have not caught are very appreciated. I've been playing around with just the multiplication for 4 hours now.
The current problem is that I am calculating the results right (like if you try x = 12 and y = 4, I will only get 8 from it, then the final answer becomes 7 which is odd) but it isn't storing properly.
definition:
MyInt operator* (const MyInt& x, const MyInt& y)
{
MyInt steps[x.numDigits - 1]; // Create an array of MyInts
int carry = 0; // Holds the 'carry the one'
int result, xInt, yInt; // For adding old-school
// Add each digit separately.
for (int i = 0; i < x.numDigits; i++)
{
steps[i].numDigits = y.numDigits; // set the numDigits to y's
// Resize the array to the size of numDigits
steps[i].Resize(steps[i].numDigits);
cout << "x.numDigits = " << x.numDigits << '\n'; // DELETE THESE
cout << "numDigits = " << steps[i].numDigits << '\n';
// Figure out xInt's value
xInt = C2I(x.myNumber[x.numDigits - i - 1]);
// Now multiply xInt by each digit of y
for (int j = 1; j <= y.numDigits; j++)
{
// yInt's value for this run through
yInt = C2I(y.myNumber[y.numDigits - j]);
// Answer is xInt * yInt + the remainder
result = ((xInt * yInt) + carry);
carry = 0; // Reset carry to zero
// If the result is 10 or higher, carry the excess
if (result > 9)
{
carry = result / 10;
result = result % 10;
}
// Assign result to the appropriate slot in the new number
steps[i].myNumber[(steps[i].numDigits - j)] = I2C(result);
cout << "ASSIGNED " << steps[i].myNumber[steps[i].numDigits - j] //DELETE THESE
<< " TO SLOT " << (steps[i].numDigits - j)
<< " with a rem = " << carry << '\n';
}
cout << "YOU GOT OUT OF THE J FOR LOOP\n";
// If carry wasn't reset to 0, that means the loop ended.
// This means there is a # that cannot fit in the current
// array size. We must resize, and then assign
// the extra characters into the array.
if (carry > 0)
{
int carryCopy = carry; // Copy of n for counting numDigits
int carryCount = 0; // Counts up how many digits are in carry
while(carryCopy > 0) // Figure out how many #'s there are
{
carryCopy = carryCopy / 10;
carryCount++;
}
// Figure out the new size
steps[i].numDigits = steps[i].numDigits + carryCount;
// Resize to new size
steps[i].Resize(steps[i].numDigits + carryCount);
// Copy in the new digits
for (int k = carryCount-1; k >= 0; k--)
{
steps[i].myNumber[k] = I2C(carry % 10);
carry = carry / 10;
}
}
}
cout << "What you have so far is " << steps[0] << "\n"; // DELETE
cout << "YOU GOT TO THE ADDING PART\n"; // DELETE
MyInt r = 0; // Create MyInt for total result
// Add up all of the arrays in steps[] into r
for (int l = 0; l < x.numDigits - 1; l++)
r = r + steps[l];
return r; // Result
}
Header file
#include <iostream>// for ostream, istream
using namespace std;
class MyInt
{
// these overload starters are declared as friend functions
friend MyInt operator+ (const MyInt& x, const MyInt& y);
friend MyInt operator* (const MyInt& x, const MyInt& y);
friend bool operator< (const MyInt& x, const MyInt& y);
friend bool operator> (const MyInt& x, const MyInt& y);
friend bool operator<= (const MyInt& x, const MyInt& y);
friend bool operator>= (const MyInt& x, const MyInt& y);
friend bool operator== (const MyInt& x, const MyInt& y);
friend bool operator!= (const MyInt& x, const MyInt& y);
friend ostream& operator<< (ostream& s, const MyInt& n);
friend istream& operator>> (istream& s, MyInt& n);
public:
MyInt(int n = 0); // first constructor
MyInt(const char * n); // second constructor
~MyInt(); // Destructor
MyInt(const MyInt & n); // Copy Constructor
MyInt& operator= (const MyInt & n); // Assignment operator
// be sure to add in the second constructor, and the user-defined
// versions of destructor, copy constructor, and assignment operator
private:
// member data (suggested: use a dynamic array to store the digits)
unsigned int numDigits; // The number of digits in myInt
char * myNumber; // Pointer to dynamic array of digits
void Resize(unsigned int newSize); // Resize array
};
and the main program I am using to test:
int main()
{
// demonstrate behavior of the two constructors and the << overload
MyInt x(12345), y("9876543210123456789"), r1(-1000), r2 = "14H67", r3;
char answer;
cout << "Initial values: \nx = " << x << "\ny = " << y
<< "\nr1 = " << r1 << "\nr2 = " << r2 << "\nr3 = " << r3 << "\n\n";
// demonstrate >> overload
cout << "Enter first number: ";
cin >> x;
cout << "Enter second number: ";
cin >> y;
cout << "You entered:\n";
cout << " x = " << x << '\n';
cout << " y = " << y << '\n';
// demonstrate assignment =
cout << "Assigning r1 = y ...\n";
r1 = y;
cout << " r1 = " << r1 << '\n';
// demonstrate comparison overloads
if (x < y) cout << "(x < y) is TRUE\n";
if (x > y) cout << "(x > y) is TRUE\n";
if (x <= y) cout << "(x <= y) is TRUE\n";
if (x >= y) cout << "(x >= y) is TRUE\n";
if (x == y) cout << "(x == y) is TRUE\n";
if (x != y) cout << "(x != y) is TRUE\n";
// demonstrating + and * overloads
r1 = x + y;
cout << "The sum (x + y) = " << r1 << '\n';
r2 = x * y;
cout << "The product (x * y) = " << r2 << "\n\n";
cout << "The sum (x + 12345) = " << x + 12345 << '\n';
cout << "The product (y * 98765) = " << y * 98765 << '\n';
}
You're doing all the multiplication first, then the adding. This is inefficient and makes your code more complicated.
Instead, you should add the results together as you compute each multiply stage.
For example, instead of:
A = 123
B = 456
S[0] = A * (B[2] * 10^2) = 123 * 400 = 49200
S[1] = A * (B[1] * 10^1) = 123 * 50 = 6150
S[2] = A * (B[0] * 10^0) = 123 * 6 = 738
R = S[0] + S[1] + S[2] = 49200 + 6150 + 738 = 56088
do this:
A = 123
B = 456
R = 0
R += A * (B[2] * 10^2) = 0 + 123 * 400 = 49200
R += A * (B[1] * 10^1) = 49200 + 123 * 50 = 55350
R += A * (B[0] * 10^0) = 55350 + 123 * 6 = 56088
This gets rid of the need for the steps array (S in my example).
Also, consider storing the digits in your array least-significant-digit first. This allows you to replace the * 10^N steps with index shifts.
A = 123
B = 456
R = 0
R[0:] += A * B[0] = 123 * 6 = 738()
R[1:] += A * B[1] = 123 * 5 + 73 = 688(8)
R[2:] += A * B[2] = 123 * 4 + 68 = 560(88)
Where the () part is the digits shifted past by the indexing of R. This technique also makes it easier to add or remove most-significant-digits since they're at the end of the array and not the beginning.
One thing I notice is that steps is initialized with a size of x.numDigits - 1 but your for loops goes past the end of the array. Perhaps you meant this steps should be of size x.numDigits. There may be other bugs than just this.
Related
When calling the function f4 how is the function returning 6? i really cant figure out how the function operates shouldnt it just return 1? because of (n-1)
#include <iostream>
#include<cmath>
#include<fstream>
using namespace std;
int x = 3;
void f1(int, int &);
int f4(int);
int main()
{
int x = 5; int y = 10;
f1(x, y);
cout << x << "\t" << y << endl;
x = 15; y = 20;
f1(x++, x);
cout << x << "\t" << y << endl;
x = 3;
cout << f4(x) << endl;
system("pause");
return 0;
}
void f1(int a, int &b)
{
a *= 2; b += x;
cout << a << "\t" << b << endl;
}
int f4(int n) {
if (n == 1 || n == 0)
return n;
else
return n + f4(n - 1);
}
The f4 function is recursive. This calling with a number other than 1 or 0 will make it recurse. You call it with 3, so the compiler (simplified) sees
f4(3) => 3 + f4(2) => 3 + 2 + f4(1) => 3 + 2 + 1 => 5 + 1 => 6
recursion in a nutshell..
int f4(int n) {
if (n == 1 || n == 0)
return n;
else
return n + f4(n - 1);
}
Your code states that when n is 1 or 0 just return n, otherwise add n to the result of the function.
that sets up a recursive stack where the first call n = 3 and it recurses.
on the next call n = 2 and it recurses.
on the next call n = 1 and it returns as well as the rest of the stack leading to 1 + 2 + 3 which is 6.
Just signed up, because my mind is blowing up on this stupid error.
I was calculating elliptic curves in a quick and dirty way with everything in 1 source-file.
Then I thought about cleaning up my code and start to separate the functions and classes in different files.
It's been a long time for me programming in C++ so I guess it is a really stupid beginner mistake.
So I am getting LNK1169-Error and LNK2005-Error and the solutions I found are about including .cpp which I am not doing. I although found out about the extern-keyword, but that seems to be kind of the solution for global variables.
Maybe someone can help me.
EDIT:
Sorry for putting that much code. I just don't know what is relevant for the error and what's not.
The error I am getting are like this:
fatal error LNK1169: one or more multiply defined symbols found. Elliptic 1 C:\Users\Björn\documents\visual studio 2015\Projects\Elliptic 1\Debug\Elliptic 1.exe
error LNK2005 "public: int __thiscall Value::operator==(class Value const &)" (??8Value##QAEHABV0##Z) already defined in Tests.obj
error LNK2005 "public: int __thiscall Value::operator==(int)" (??8Value##QAEHH#Z) already defined in Tests.obj
Here is my code:
Value.hpp
#pragma once
extern int PRIME;
// An own Int-Class to overload operators with modulo
class Value
{
public:
int v;
static friend std::ostream& operator<<(std::ostream& os, const Value& a);
Value()
{
this->v = 0;
}
Value(int a)
{
this->v = a;
}
Value operator+(const Value& other)
{
return Value((this->v + other.v) % PRIME);
}
Value operator+(int a)
{
return Value((this->v + a) % PRIME);
}
Value operator-(const Value& other)
{
Value t = Value((v - other.v) % PRIME);
if (t.v < 0)
{
t = t + PRIME;
return t;
}
return t;
}
Value operator-(int a)
{
Value t = Value((v - a) % PRIME);
if (t.v < 0)
{
t = t + PRIME;
return t;
}
return t;
}
void operator=(const Value other)
{
this->v = other.v;
}
Value operator*(const Value& a);
Value operator*(int a);
Value operator^(int a);
Value operator/(const Value& a);
int operator!=(int b);
int operator!=(const Value& b);
int operator==(int b);
int operator==(const Value& b);
Value operator~();
};
Value Value::operator*(const Value& a)
{
return Value((this->v*a.v) % PRIME);
}
Value Value::operator*(int a)
{
return Value((this->v*a) % PRIME);
}
Value Value::operator^(int b)
{
Value ret(1);
Value mul(this->v);
while (b)
{
if (b & 1)
ret = (ret * mul);
b = (b >> 1);
mul = mul * mul;
}
return ret;
}
Value Value::operator/(const Value& a)
{
if (a.v == 0)
return Value(0);
Value f = (Value)a ^ (PRIME - 2);
return *this * f;
}
int Value::operator!=(int b)
{
if (this->v != b)
return 1;
return 0;
}
int Value::operator!=(const Value& b)
{
if (this->v != b.v)
return 1;
return 0;
}
int Value::operator==(int b)
{
if (this->v == b)
return 1;
return 0;
}
int Value::operator==(const Value& b)
{
if (this->v == b.v)
return 1;
return 0;
}
Value Value::operator~()
{
return *this ^ ((PRIME - 1 + 2) / 4);
}
std::ostream& operator<<(std::ostream& os, const Value& a)
{
return os << a.v;
}
Point.hpp
#pragma once
#include "Value.hpp"
#include <iostream>
class Point
{
public:
Value x;
Value y;
Value z = 0;
static friend std::ostream& operator<<(std::ostream& os, const Point& p);
Point(int a, int b)
{
x.v = a;
y.v = b;
}
Point(int a, int b, int c)
{
x.v = a;
y.v = b;
z.v = c;
}
Point(Value a, Value b)
{
x.v = a.v;
y.v = b.v;
}
Point(Value a, Value b, Value c)
{
x.v = a.v;
y.v = b.v;
z.v = c.v;
}
Point& operator=(const Point& other)
{
x.v = other.x.v;
y.v = other.y.v;
z.v = other.z.v;
return *this;
}
int operator==(Point& other)
{
if (this->x == other.x && this->y == other.y && this->z == other.z)
return 1;
return 0;
}
int operator!=(Point& other)
{
if (this->x != other.x || this->y != other.y || this->z != other.z)
return 1;
return 0;
}
};
std::ostream& operator<<(std::ostream& os, const Point& p)
{
if ((Value)p.z == 0)
return os << "(" << p.x.v << "," << p.y.v << ")";
else
return os << "(" << p.x.v << "," << p.y.v << "," << p.z.v << ")";
}
Helper.hpp
#pragma once
#include "Point.hpp"
#include <vector>
// Forward declaration
int isEC(Value a, Value b);
Value calcEC(int x, Value a, Value b);
int testSqr(Value ySqr);
// Point Addition
Point add(Point p1, Point p2, Value a)
{
// 2D Addition
if (p1.z == 0 && p2.z == 0)
{
// 2 different points
if (p1.x.v != p2.x.v || p1.y.v != p2.y.v)
{
// m = (y2-y1)/(x2-x1)
Value h = p2.y - p1.y;
Value j = p2.x - p1.x;
Value m = h / j;
// x3 = m^2-x1-x2
Value f = m*m;
Value g = f - p1.x;
Value x3 = g - p2.x;
// y3 = m(x1-x3)-y1
Value t = p1.x - x3;
Value l = m * t;
Value y3 = l - p1.y;
if (x3.v < 0)
x3 = x3 + PRIME;
if (y3.v < 0)
y3 = y3 + PRIME;
return Point(x3, y3);
}
// Same points
else
{
// m = (3*x1^2+a)/(2*y1)
Value f = p1.x ^ 2;
Value g = f * 3;
Value h = g + a;
Value j = p1.y * 2;
Value m = h / j;
// x3 = m^2-2*x1
Value t = m*m;
Value x = p1.x * 2;
Value x3 = t - x;
// y3 = m(x1-x3)-y1
Value z = p1.x - x3;
Value i = m * z;
Value y3 = i - p1.y;
if (x3.v < 0)
x3 = x3 + PRIME;
if (y3.v < 0)
y3 = y3 + PRIME;
return Point(x3, y3);
}
}
// 3D Addition - Same points
else if (p1 == p2 && p1.z == 1 && p2.z == 1)
{
Value A = p1.y ^ 2;
Value B = p1.x * A * 4;
Value C = (A ^ 2) * 8;
Value D = (p1.x ^ 2)* 3 + a*(p1.z ^ 4);
//Value x3 = (((3 * (p1.x ^ 2) + a*(p1.z ^ 4)) ^ 2) - 8 * p1.x*(p1.y ^ 2));
Value x3 = (D ^ 2) - B * 2;
//Value y3 = (3 * (p1.x ^ 2) + a*(p1.z ^ 4)*(4 * p1.x*(p1.y ^ 2) - x3) - 8 * (p1.y ^ 4));
Value y3 = D*(B - x3) - C;
Value z3 = p1.y*p1.z * 2;
return Point(x3, y3, z3);
}
// 3D Addition - 2 different points
else if (p1 != p2)
{
Value A = p1.z ^ 2;
Value B = p1.z * A;
Value C = p2.x * A;
Value D = p2.y * B;
Value E = C - p1.x;
Value F = D - p1.y;
Value G = E ^ 2;
Value H = G * E;
Value I = p1.x * G;
Value x3 = (F ^ 2) - (H + (I * 2));
Value y3 = F*(I - x3) - p1.y*H;
Value z3 = p1.z * E;
return Point(x3, y3, z3);
}
return Point(0, 0, 0);
}
// Find all points and print them
std::vector<Point> findAllPoints(Value a, Value b)
{
Value ySqr;
std::vector<Point> vec;
std::cout << "Alle Punkte fuer a = " << a << ", b = " << b << " und Prime = " << PRIME << std::endl;
// Is it an elliptic curve?
if (isEC(a, b))
{
// Test all x-Values
for (int x = 0; x <= PRIME - 1;x++)
{
// y^2
ySqr = calcEC(x, a, b);
// Test ySqr for square by root
if (testSqr(ySqr))
{
//sqrt operator ~
Value yPos = ~ySqr;
std::cout << "(" << x << "," << yPos << ")\t";
Value yNeg = yPos - (yPos * 2);
// Save found points into vector
vec.push_back(Point(x, yPos));
vec.push_back(Point(x, yNeg));
if (yNeg != 0)
std::cout << "(" << x << "," << yNeg << ")\t";
}
}
//vec.insert(vec.begin(), Point(INFINITY, INFINITY));
std::cout << std::endl;
}
else
// Not an ellpitic curve
std::cout << "\na and b are not leading to an ellptic curve.";
return vec;
}
// Test if a and b lead to an EC
int isEC(Value a, Value b)
{
if ((a ^ 3) * 4 + (b ^ 2) * 27 != 0)
return 1;
return 0;
}
// Calculate y^2
Value calcEC(int x, Value a, Value b)
{
return Value(a*x + (x ^ 3) + b);
}
// Test ySqr for square by root
int testSqr(Value ySqr)
{
if ((ySqr ^ ((PRIME - 1) / 2)) == 1 || ySqr == 0)
return 1;
return 0;
}
Tests.hpp
#pragma once
#include "Helper.hpp"
class Tests
{
public:
void twoDAdd(Value a, Value b);
void twoDDoubling(Value a, Value b);
void threeDAdd(Value a, Value b);
void threeDDoubling(Value a, Value b);
};
Tests.cpp
#pragma once
#include <stdlib.h>
#include <vector>
#include <iostream>
#include <math.h>
#include <time.h>
#include "Tests.hpp"
// 2D - Addition
void Tests::twoDAdd(Value a, Value b)
{
std::cout << "\n========== 2D Addition ==========\n";
Point p2D1 = Point(5, 22);
Point p2D2 = Point(16, 27);
std::cout << p2D1 << " + " << p2D2 << " = " << add(p2D1, p2D2, a);
std::cout << std::endl;
}
// 2D - Doubling
void Tests::twoDDoubling(Value a, Value b)
{
std::cout << "\n========== 2D Doubling ==========\n";
Point p2D1 = Point(5, 22);
std::cout << "2 * " << p2D1 << " = " << add(p2D1, p2D1, a);
std::cout << std::endl << std::endl;
}
// 3D - Addition
void Tests::threeDAdd(Value a, Value b)
{
std::cout << "\n========== 3D Addition ==========\n";
std::cout << "All points for a = " << a << ", b = " << b << " and prime = " << PRIME << std::endl;
std::vector<Point> allPoints = findAllPoints(a, b);
std::srand(time(NULL));
int random = std::rand() % (allPoints.capacity() - 1);
Point tmp = allPoints.at(random);
std::cout << std::endl << "Random Point 1: " << tmp << std::endl << std::endl;
tmp.z = 1;
Point p1 = add(tmp, tmp, a);
std::cout << p1 << std::endl;
random = std::rand() % (allPoints.capacity() - 1);
tmp = allPoints.at(random);
std::cout << std::endl << "Random Point 2: " << tmp << std::endl << std::endl;
tmp.z = 1;
Point p2 = add(tmp, tmp, a);
std::cout << p2 << std::endl;
Point p3 = add(p1, p2, a);
std::cout << p3 << std::endl;
}
// 3D - Doubling
void Tests::threeDDoubling(Value a, Value b)
{
std::cout << "\n========== 3D Doubling ==========\n";
std::cout << "All points for a = " << a << ", b = " << b << " and prime = " << PRIME << std::endl;
std::vector<Point> allPoints = findAllPoints(a, b);
int random = std::rand() % (allPoints.capacity() - 1);
Point tmp = allPoints[random];
std::cout << std::endl << "Random Point: " << tmp << std::endl << std::endl;
Point p1 = add(tmp, tmp, a);
std::cout << p1 << std::endl;
tmp.z = 1;
Point p2 = add(tmp, tmp, a);
std::cout << p2 << std::endl;
Point p3 = Point(p2.x / (p2.z ^ 2), p2.y / (p2.z ^ 3));
std::cout << p3 << std::endl;
if (p1 == p3)
std::cout << "Point p1 == Point p3" << std::endl;
else
std::cout << "Point p1 != Point p3" << std::endl;
}
Main.cpp
#pragma once
#include <stdlib.h>
#include <vector>
#include <iostream>
#include <math.h>
#include <time.h>
#include "Tests.hpp"
int PRIME = 29;
void main()
{/*
Value a = 4;
Value b = 20;
std::vector<Point> allPoints = findAllPoints(a, b);
/*
// Tests ausfuehren
twoDAdd(a, b);
twoDDoubling(a, b);
threeDAdd(a, b);
threeDDoubling(a, b);
*/
std::cout << std::endl;
system("pause");
}
Thanks in advance and please excuse my "inperfect" way of coding.
This is happening because you have function definition in header files. Every file that we'll import your header files will have a body function - this is the reason why you have this error. If you want to have the definitions inside header files, you must use inline keyword. Otherwise you need to implement them in .cpp files (the "correct" way of solving this issue).
e.g
// Test if a and b lead to an EC
inline int isEC(Value a, Value b)
{
if ((a ^ 3) * 4 + (b ^ 2) * 27 != 0)
return 1;
return 0;
}
// Calculate y^2
inline Value calcEC(int x, Value a, Value b)
{
return Value(a*x + (x ^ 3) + b);
}
// Test ySqr for square by root
inline int testSqr(Value ySqr)
{
if ((ySqr ^ ((PRIME - 1) / 2)) == 1 || ySqr == 0)
return 1;
return 0;
}
I wrote a C++ routine to find nearest double element in sorted array. Is there a way to speed up?
There are two branches based on the value of boolean reversed, if reversed it is sorted in the decreasing order.
void findNearestNeighbourIndex_new(real_T value, real_T* x, int_T x_size, int_T& l_idx)
{
l_idx = -1;
bool reversed= (x[1] - x[0] < 0);
if ((!reversed&& value <= x[0])
|| (reversed&& value >= x[0])){
// Value is before first position in x
l_idx = 0;
}
else if ((!reversed&& value >= x[x_size - 1])
|| (reversed&& value <= x[x_size - 1])){
// Value is after last position in x
l_idx = x_size - 2;
}
else // All other cases
{
if (reversed)
{
for (int i = 0; i < x_size - 1; ++i)
{
if (value <= x[i] && value > x[i + 1])
{
l_idx = i;
break;
}
}
}
else{
for (int i = 0; i < x_size - 1; ++i)
{
if (value >= x[i] && value < x[i + 1])
{
l_idx = i;
break;
}
}
}
}
}
In this very case where array is sorted, I do not see a way to do better. So, with profiling i see that the comparison in if (value <= x[i] && value > x[i + 1]) is expensive.
EDIT
tried with lower_bound()
std::vector<real_T> x_vec(x, x + x_size);
l_idx = std::upper_bound(x_vec.begin(), x_vec.end(), value) - x_vec.begin() - 1;
You can use std::lower_bound to find a element equal or greater than requested, and then move iterator backwards and check preceding value too. This will use binary search and will cost O(log n), also this enables standard STL comparators and so on.
If you don't actually have an vector to use with upper_bound() you don't need to construct one as that is going to be an O(n) operation. upper_bound() will work with the array that you have. You can use:
l_idx = std::upper_bound(x, x + size, value) - x - 1;
Test case:
#include <iostream>
#include <functional>
#include <algorithm>
int main()
{
const int size = 9;
int x[9] = {1,2,3,4,5,6,7,8,9};
auto pos = std::upper_bound(x, x + size, 5) - x;
std::cout << "position: " << pos;
return 0;
}
Output:
5
As the result of upper_bound() points us to 6(live example).
The way is to substract 1 to size (to make work over higest value) and 0.5 to target value to make it accurate:
#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;
int main()
{
float x[10] = { 2,3,4,5,6,7,8,9,10,11 },y;
int size = sizeof(x) / sizeof(x[0]),pos;
y = 4.1; pos = std::upper_bound(x, x + size - 1, y - 0.5) - x;
std::cout << "position: " << pos << " target value=" << y << " upper_bound=" << x[pos] << endl;
y = 4.9; pos = std::upper_bound(x, x + size - 1, y - 0.5) - x;
std::cout << "position: " << pos << " target value=" << y << " upper_bound=" << x[pos] << endl;
y = -0.5; pos = std::upper_bound(x, x + size - 1, y - 0.5) - x;
std::cout << "position: " << pos << " target value=" << y << " upper_bound=" << x[pos] << endl;
y = 100; pos = std::upper_bound(x, x + size - 1, y - 0.5) - x;
std::cout << "position: " << pos << " target value=" << y << " upper_bound=" << x[pos] << endl;
getchar();
return 0;
}
Implemented this helper routine
void findNearestNeighbourIndex_bin_search_new(real_T value, real_T* x,
int_T start, int_T stop, int_T& l_idx)
{
int_T mid = ( stop - start ) / 2;
if (value >= x[mid+1])
{
findNearestNeighbourIndex_bin_search_new(value, x, mid + 1, stop, l_idx);
}
else if (value < x[mid])
{
findNearestNeighbourIndex_bin_search_new(value, x, start, mid, l_idx);
}
else
{
l_idx = mid;
return;
}
}
// Function as parameter of a function
#include <iostream>
#include <cmath>
#include <cassert>
using namespace std;
const double PI = 4 * atan(1.0); // tan^(-1)(1) == pi/4 then 4*(pi/4)== pi
typedef double(*FD2D)(double);
double root(FD2D, double, double); //abscissae of 2-points,
//For the algorithm to work, the function must assume values of opposite sign in these two points, check
// at point 8
double polyn(double x) { return 3 - x*(1 + x*(27 - x * 9)); }
int main() {
double r;
cout.precision(15);
r = root(sin, 3, 4);
cout << "sin: " << r << endl
<< "exactly: " << PI << endl << endl;
r = root(cos, -2, -1.5);
cout << "cos: " << r << endl
<< "exactly: " << -PI/2 << endl << endl;
r = root(polyn, 0, 1);
cout << "polyn: " << r << endl
<< "exactly: " << 1./3 << endl << endl;
/*
we look for the root of the function equivalent to function polyn
but this time defined as a lambda function
*/
r = root([](double x) -> double {
return 3 - x*(1 + x*(27 - x * 9));
}, 0, 1);
cout << "lambda: " << r << endl
<< "exactly: " << 1. / 3 << endl << endl;
return 0;
}
// Finding root of function using bisection.
// fun(a) and fun(b) must be of opposite sign
double root(FD2D fun, double a, double b) {
static const double EPS = 1e-15; // 1×10^(-15)
double f, s, h = b - a, f1 = fun(a), f2 = fun(b);
if (f1 == 0) return a;
if (f2 == 0) return b;
assert(f1*f2<0); // 8.- macro assert from header cassert.
do {
if ((f = fun((s = (a + b) / 2))) == 0) break;
if (f1*f2 < 0) {
f2 = f;
b = s;
}
else {
f1 = f;
a = s;
}
} while ((h /= 2) > EPS);
return (a + b) / 2;
}
Could somebody explain me how the loop in double root function works? I don't seem to understand 100%, I checked this bisection method online and try on paper, but I can't manage to figure it out from this example.
Thanks in advance!
It's a lot easier to understand if you split the "clever" line into multiple lines. Here's some modifications, plus comments:
double root(FD2D fun, double a, double b) {
static const double EPS = 1e-15; // 1×10^(-15)
double fa = fun(a), fb = fun(b);
// if either f(a) or f(b) are the root, return that
// nothing else to do
if (fa == 0) return a;
if (fb == 0) return b;
// this method only works if the signs of f(a) and f(b)
// are different. so just assert that
assert(fa * fb < 0); // 8.- macro assert from header cassert.
do {
// calculate fun at the midpoint of a,b
// if that's the root, we're done
// this line is awful, never write code like this...
//if ((f = fun((s = (a + b) / 2))) == 0) break;
// prefer:
double midpt = (a + b) / 2;
double fmid = fun(midpt);
if (fmid == 0) return midpt;
// adjust our bounds to either [a,midpt] or [midpt,b]
// based on where fmid ends up being. I'm pretty
// sure the code in the question is wrong, so I fixed it
if (fa * fmid < 0) { // fmid, not f1
fb = fmid;
b = midpt;
}
else {
fa = fmid;
a = midpt;
}
} while (b-a > EPS); // only loop while
// a and b are sufficiently far
// apart
return (a + b) / 2; // approximation
}
I have the equation of a 2D line in the General Form a x + b y + c = 0 and I need to convert it to the proper Slope-intercept Form; with proper I mean I can choose between y = m x + q and x = m y + q.
My idea is to check if the line appears "more" horizontal or vertical and consequently choose one of the two Slope-intercept Form.
This is a sample code:
#include <iostream>
#include <cmath>
void abc2mq( double a, double b, double c, double& m, double& q, bool& x2y )
{
if ( fabs(b) >= fabs(a) ) {
x2y = true;
m = -a/b;
q = -c/b;
} else {
x2y = false;
m = -b/a;
q = -c/a;
}
}
void test(double a, double b, double c)
{
double m,q;
bool x2y;
abc2mq( a, b, c, m, q, x2y );
std::cout << a << " x + " << b << " y + " << c << " = 0\t";
if ( x2y ) {
std::cout << "y = " << m << " x + " << q << "\n";
} else {
std::cout << "x = " << m << " y + " << q << "\n";
}
}
int main(int argc, char* argv[])
{
test(0,0,0);
test(0,0,1);
test(0,1,0);
test(0,1,1);
test(1,0,0);
test(1,0,1);
test(1,1,0);
test(1,1,1);
return 0;
}
And this is the output
0 x + 0 y + 0 = 0 y = -1.#IND x + -1.#IND
0 x + 0 y + 1 = 0 y = -1.#IND x + -1.#INF
0 x + 1 y + 0 = 0 y = -0 x + -0
0 x + 1 y + 1 = 0 y = -0 x + -1
1 x + 0 y + 0 = 0 x = -0 y + -0
1 x + 0 y + 1 = 0 x = -0 y + -1
1 x + 1 y + 0 = 0 y = -1 x + -0
1 x + 1 y + 1 = 0 y = -1 x + -1
Any different or better idea? In particular, how can I handle the first two "degenerate" lines?
If you are looking for a good way to draw these lines, I would recommend using Bresenham's algorithm instead of sampling the result of the slope-intercept form of your line equation.
Apologies if this is not what you are trying to do.
You're almost done, just handle the degenerate case.
Add the check for a and b to be non-zero.
if(fabs(a) > DBL_EPSILON && fabs(b) > DBL_EPSILON)
{
... non-degenerate line handling
} else
{
// both a and b are machine zeros
degenerate_line = true;
}
Then add the parameter 'degenerate_line':
void abc2mq( double a, double b, double c, double& m, double& q, bool& x2y, bool& degenerate_line)
{
if(fabs(a) > DBL_EPSILON && fabs(b) > DBL_EPSILON)
{
if ( fabs(b) >= fabs(a) ) {
x2y = true;
m = -a/b;
q = -c/b;
} else {
x2y = false;
m = -b/a;
q = -c/a;
}
degenerate_line = false;
} else
{
degenerate_line = true;
}
}
And then check for the line to be empty set:
void test(double a, double b, double c)
{
double m,q;
bool x2y, degenerate;
abc2mq( a, b, c, m, q, x2y, degenerate );
std::cout << a << " x + " << b << " y + " << c << " = 0\t";
if(!degenerate)
{
if ( x2y ) {
std::cout << "y = " << m << " x + " << q << std::endl;
} else {
std::cout << "x = " << m << " y + " << q << std::endl;
}
} else
{
if(fabs(c) > DBL_EPSILON)
{
std::cout << "empty set" << std::endl
} else
{
std::cout << "entire plane" << std::endl
}
}
}
If all you need is to draw the line, just use Thorsten's advice - use the rasterization algorithm instead.
The equations corresponding to the two degenerated cases do not represent lines but the full plane (ℝ2) and the empty set (∅) respectively. The right thing to do is probably to discard them or to throw an error.
For the non degenerate cases, you are already handling them properly.