Re: writing an external function in std c++
On 19 Feb., 11:41, Richard Herring <junk@[127.0.0.1]> wrote:
In message
<bcf7a69f-fe17-42ac-bc8a-11da4622c...@s13g2000prd.googlegroups.com>,
peter koch <peter.koch.lar...@gmail.com> writes
On 18 Feb., 06:41, "Gerry Ford" <inva...@invalid.net> wrote:
I've been pecking away at writing a program that will calculate the inner
product of two double-width four-vectors.
Why? There are libraries that do this better than you or I could
reasonably hope to do unless we really took the time (and perhaps even
then! ;-)).
I am quite sure of that even if I don't really know what double-width
and four-vector is. These are neither terms of C++ nor of mathematics.
"Four-vector" is a standard term in relativistic physics.
Larry thinks I'm well started with the following source to populate a
vector:
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <math.h>
int main() {
std::vector<double> four_vector;
for (double i=0.0; i<4.0; i++)
four_vector.push_back(sqrt(i));
This loop is really dangerous. You risk having five elements in your
vector.
With probability approaching zero. I doubt if there are _any_
floating-point implementations where a double can't exactly represent
all integers up to some value considerably larger than a 32-bit int, and
perform exact arithmetic on them. Even a float can count up to 4 without
error.
I fully agree with you here. I saw a loop controled by a double and my
gut instinct told me that this was bad. Having integer increments make
this safe, of course so there is no reason to worry.
Also it is inefficient as you (presumably!) know that there
should be four elements in the vector.
_Measurably_ inefficient?
Use reserve
You really think it will help? The very first push_back will do
something internally equivalent to reserve(N) for some N which quite
likely exceeds 4.
Perhaps. I have not examined my implementation but would expect it to
have reserves of 1, 2 and four.
or prefer a fixed-size vector which imo is the best
solution provided that you will always have a fixed number of elements
in your vector.
There may well be a good argument for having a dedicated class
representing four-vectors, but this isn't it.
If all your four-vectors are dynamically allocated, I would expect new/
delete to easily dominate some types of computations - all depending
on how many temporaries you need, of course.
/Peter