Search Results

Search found 6094 results on 244 pages for 'double gras'.

Page 38/244 | < Previous Page | 34 35 36 37 38 39 40 41 42 43 44 45  | Next Page >

  • How to efficiently convert String, integer, double, datetime to binary and vica versa?

    - by Ben
    Hi, I'm quite new to C# (I'm using .NET 4.0) so please bear with me. I need to save some object properties (their properties are int, double, String, boolean, datetime) to a file. But I want to encrypt the files using my own encryption, so I can't use FileStream to convert to binary. Also I don't want to use object serialization, because of performance issues. The idea is simple, first I need to somehow convert objects (their properties) to binary (array), then encrypt (some sort of xor) the array and append it to the end of the file. When reading first decrypt the array and then somehow convert the binary array back to object properties (from which I'll generate objects). I know (roughly =) ) how to convert these things by hand and I could code it, but it would be useless (too slow). I think the best way would be just to get properties' representation in memory and save that. But I don't know how to do it using C# (maybe using pointers?). Also I though about using MemoryStream but again I think it would be inefficient. I am thinking about class Converter, but it does not support toByte(datetime) (documentation says it always throws exception). For converting back I think the only options is class Converter. Note: I know the structure of objects and they will not change, also the maximum String length is also known. Thank you for all your ideas and time. EDIT: I will be storing only parts of objects, in some cases also parts of different objects (a couple of properties from one object type and a couple from another), thus I think that serialization is not an option for me.

    Read the article

  • "Forced constness" in std::map<std::vector<int>,double> > ?

    - by Peter Jansson
    Consider this program: #include <map> #include <vector> typedef std::vector<int> IntVector; typedef std::map<IntVector,double> Map; void foo(Map& m,const IntVector& v) { Map::iterator i = m.find(v); i->first.push_back(10); }; int main() { Map m; IntVector v(10,10); foo(m,v); return 0; } Using g++ 4.4.0, I get his compilation error: test.cpp: In function 'void foo(Map&, const IntVector&)': test.cpp:8: error: passing 'const std::vector<int, std::allocator<int> >' as 'this' argument of 'void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = int, _Alloc = std::allocator<int>]' discards qualifiers I would expect this error if I was using Map::const_iterator inside foo but not using a non-const iterator. What am I missing, why do I get this error?

    Read the article

  • How can I prevent double file uploading with Amazon S3?

    - by Tony
    I decided to use Amazon S3 for document storage for an app I am creating. One issue I run into is while I need to upload the files to S3, I need to create a document object in my app so my users can perform CRUD actions. One solution is to allow for a double upload. A user uploads a document to the server my Rails app lives on. I validate and create the object, then pass it on to S3. One issue with this is progress indicators become more complicated. Using most out-of-the-box plugins would show the client that file has finished uploading because it is on my server, but then there would be a decent delay when the file was going from my server to S3. This also introduces unnecessary bandwidth (at least it does not seem necessary) The other solution I am thinking about is to upload the file directly to S3 with one AJAX request, and when that is successful, make a second AJAX request to store the object in my database. One issue here is that I would have to validate the file after it is uploaded which means I have to run some clean up code in S3 if the validation fails. Both seem equally messy. Does anyone have something more elegant working that they would not mind sharing? I would imagine this is a common situation with "cloud storage" being quite popular today. Maybe I am looking at this wrong.

    Read the article

  • Formatting the output of a custom tool so I can double click an error in Visual Studio and the file opens

    - by Ben Scott
    I've written a command line tool that preprocesses a number of files then compiles them using CodeDom. The tool writes a copyright notice and some progress text to the standard output, then writes any errors from the compilation step using the following format: foreach (var err in results.Errors) { // err is CompilerError var filename = "Path\To\input_file.xprt"; Console.WriteLine(string.Format( "{0} ({1},{2}): {3}{4} ({5})", filename, err.Line, err.Column, err.IsWarning ? "" : "ERROR: ", err.ErrorText, err.ErrorNumber)); } It then writes the number of errors, like "14 errors". This is an example of how the error appears in the console: Path\To\input_file.xrpt (73,28): ERROR: An object reference is required for the non-static field, method, or property 'Some.Object.get' (CS0120) When I run this as a custom tool in VS2008 (by calling it in the post-build event command line of one of my project's assemblies), the errors appear nicely formatted in the Error List, with the correct text in each column. When I roll over the filename the fully qualified path pops up. The line and column are different to the source file because of the preprocessing which is fine. The only thing that stands out is that the Project given in the list is the one that has the post-build event. The problem is that when I double click an error, nothing happens. I would have expected the file to open in the editor. I'm vaugely aware of the Microsoft.VisualStudio.Shell.Interop namespace but I think it should be possible just by writing to the standard output.

    Read the article

  • Why is my Android app force closing when I try to check if an EditText has a double

    - by user336861
    Scanner scanner = new Scanner(lapsPerMile_st); if (!scanner.hasNextDouble()) { Context context = getApplicationContext(); String msg = "Please Enter Digits and Decmials Only"; int duration = Toast.LENGTH_LONG; Toast.makeText(context, msg, duration).show(); lapsPerMileEditText.setText(""); return; } else { //Edit box has only digits, Set data and display stats data.setLapsPerMile(Integer.parseInt(lapsPerMile_st)); lapsRunLabel.setVisibility(0); lapsRunTextView.setText(Integer.toString(data.getLapsRun())); milesRunLabel.setVisibility(0); milesRunTextView.setText(Double.toString(data.getLapsRun()/data.getLapsPerMile())); } <EditText android:id="@+id/mileCount" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_marginTop="110dp" android:inputType="numberDecimal" android:maxLength="4" /> For some reason if I enter a non decimal number such as 3, or 5, it works fine but when I enter a floating point such as 3.4 or 5.8 it force closes. I cant seem to figure out whats going on. Any ideas? Thanks

    Read the article

  • Is there a Java data structure that is effectively an ArrayList with double indicies and built-in in

    - by Bob Cross
    I am looking for a pre-built Java data structure with the following characteristics: It should look something like an ArrayList but should allow indexing via double-precision rather than integers. Note that this means that it's likely that you'll see indicies that don't line up with the original data points (i.e., asking for the value that corresponds to key "1.5"). As a consequence, the value returned will likely be interpolated. For example, if the key is 1.5, the value returned could be the average of the value at key 1.0 and the value at key 2.0. The keys will be sorted but the values are not ensured to be monotonically increasing. In fact, there's no assurance that the first derivative of the values will be continuous (making it a poor fit for certain types of splines). Freely available code only, please. For clarity, I know how to write such a thing. In fact, we already have an implementation of this and some related data structures in legacy code that I want to replace due to some performance and coding issues. What I'm trying to avoid is spending a lot of time rolling my own solution when there might already be such a thing in the JDK, Apache Commons or another standard library. Frankly, that's exactly the approach that got this legacy code into the situation that it's in right now.... Is there such a thing out there in a freely available library?

    Read the article

  • How to efficiently get highest & lowest values from a List<double?>, and then modify them?

    - by DaveDev
    I have to get the sum of a list of doubles. If the sum is 100, I have to decrement from the highest number until it's = 100. If the sum is < 100, I have to increment the lowest number until it's = 100. I can do this by looping though the list, assigning the values to placeholder variables and testing which is higher or lower but I'm wondering if any gurus out there could suggest a super cool & efficient way to do this? The code below basically outlines what I'm trying to achieve: var splitValues = new List<double?>(); splitValues.Add(Math.Round(assetSplit.EquityTypeSplit() ?? 0)); splitValues.Add(Math.Round(assetSplit.PropertyTypeSplit() ?? 0)); splitValues.Add(Math.Round(assetSplit.FixedInterestTypeSplit() ?? 0)); splitValues.Add(Math.Round(assetSplit.CashTypeSplit() ?? 0)); var listSum = splitValues.Sum(split => split.Value); if (listSum != 100) { if (listSum > 100) { // how to get highest value and decrement by 1 until listSum == 100 // then reassign back into the splitValues list? var highest = // ?? } else { // how to get lowest where value is > 0, and increment by 1 until listSum == 100 // then reassign back into the splitValues list? var lowest = // ?? } } update: the list has to remain in the same order as the items are added.

    Read the article

  • Convert RGB value to HSV

    - by marionmaiden
    I've found a method on the Internet to convert RGB values to HSV values. Unfortunately, when the values are R=G=B, I'm getting a NaN, because of the 0/0 operation. Do you know if there is an implemented method for this conversion in Java, or what do I have to do when I get the 0/0 division to get the right value of the HSV? Here comes my method, adapted from some code on the Internet: public static double[] RGBtoHSV(double r, double g, double b){ double h, s, v; double min, max, delta; min = Math.min(Math.min(r, g), b); max = Math.max(Math.max(r, g), b); // V v = max; delta = max - min; // S if( max != 0 ) s = delta / max; else { s = 0; h = -1; return new double[]{h,s,v}; } // H if( r == max ) h = ( g - b ) / delta; // between yellow & magenta else if( g == max ) h = 2 + ( b - r ) / delta; // between cyan & yellow else h = 4 + ( r - g ) / delta; // between magenta & cyan h *= 60; // degrees if( h < 0 ) h += 360; return new double[]{h,s,v}; }

    Read the article

  • SQLiteDataAdapter Fill exception C# ADO.NET

    - by Lirik
    I'm trying to use the OleDb CSV parser to load some data from a CSV file and insert it into a SQLite database, but I get an exception with the OleDbAdapter.Fill method and it's frustrating: An unhandled exception of type 'System.Data.ConstraintException' occurred in System.Data.dll Additional information: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints. Here is the source code: public void InsertData(String csvFileName, String tableName) { String dir = Path.GetDirectoryName(csvFileName); String name = Path.GetFileName(csvFileName); using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + @";Extended Properties=""Text;HDR=No;FMT=Delimited""")) { conn.Open(); using (OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + name, conn)) { QuoteDataSet ds = new QuoteDataSet(); adapter.Fill(ds, tableName); // <-- Exception here InsertData(ds, tableName); // <-- Inserts the data into the my SQLite db } } } class Program { static void Main(string[] args) { SQLiteDatabase target = new SQLiteDatabase(); string csvFileName = "D:\\Innovations\\Finch\\dev\\DataFeed\\YahooTagsInfo.csv"; string tableName = "Tags"; target.InsertData(csvFileName, tableName); Console.ReadKey(); } } The "YahooTagsInfo.csv" file looks like this: tagId,tagName,description,colName,dataType,realTime 1,s,Symbol,symbol,VARCHAR,FALSE 2,c8,After Hours Change,afterhours,DOUBLE,TRUE 3,g3,Annualized Gain,annualizedGain,DOUBLE,FALSE 4,a,Ask,ask,DOUBLE,FALSE 5,a5,Ask Size,askSize,DOUBLE,FALSE 6,a2,Average Daily Volume,avgDailyVolume,DOUBLE,FALSE 7,b,Bid,bid,DOUBLE,FALSE 8,b6,Bid Size,bidSize,DOUBLE,FALSE 9,b4,Book Value,bookValue,DOUBLE,FALSE I've tried the following: Removing the first line in the CSV file so it doesn't confuse it for real data. Changing the TRUE/FALSE realTime flag to 1/0. I've tried 1 and 2 together (i.e. removed the first line and changed the flag). None of these things helped... One constraint is that the tagId is supposed to be unique. Here is what the table look like in design view: Can anybody help me figure out what is the problem here?

    Read the article

  • CIL and JVM Little endian to big endian in c# and java

    - by Haythem
    Hello, I am using on the client C# where I am converting double values to byte array. I am using java on the server and I am using writeDouble and readDouble to convert double values to byte arrays. The problem is the double values from java at the end are not the double values at the begin giving to c# writeDouble in Java Converts the double argument to a long using the doubleToLongBits method , and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first. DoubleToLongBits Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "double format" bit layout. The Program on the server is waiting of 64-102-112-0-0-0-0-0 from C# to convert it to 1700.0 but he si becoming 0000014415464 from c# after c# converted 1700.0 this is my code in c#: class User { double workingStatus; public void persist() { byte[] dataByte; using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(workingStatus); bw.Flush(); bw.Close(); } dataByte = ms.ToArray(); for (int j = 0; j < dataByte.Length; j++) { Console.Write(dataByte[j]); } } public double WorkingStatus { get { return workingStatus; } set { workingStatus = value; } } } class Test { static void Main() { User user = new User(); user.WorkingStatus = 1700.0; user.persist(); } thank you for the help.

    Read the article

  • C function const multidimensional-array argument strange warning

    - by rogi
    Ehllo, I'm getting some strange warning about this code: typedef double mat4[4][4]; void mprod4(mat4 r, const mat4 a, const mat4 b) { /* yes, function is empty */ } int main() { mat4 mr, ma, mb; mprod4(mr, ma, mb); } gcc output as follows: $ gcc -o test test.c test.c: In function 'main': test.c:13: warning: passing argument 2 of 'mprod4' from incompatible pointer type test.c:4: note: expected 'const double (*)[4]' but argument is of type 'double (*)[4]' test.c:13: warning: passing argument 3 of 'mprod4' from incompatible pointer type test.c:4: note: expected 'const double ()[4]' but argument is of type 'double ()[4]' defining the function as: void mprod4(mat4 r, mat4 a, mat4 b) { } OR defining matrices at main as: mat4 mr; const mat4 ma; const mat4 mb; OR calling teh function in main as: mprod4(mr, (const double(*)[4])ma, (const double(*)[4])mb); OR even defining mat4 as: typedef double mat4[16]; make teh warning go away. Wat is happening here? Am I doing something invalid? gcc version is 4.4.3 if relevant. Thanks for your attention.

    Read the article

  • Call by Reference Function in C

    - by Chad
    Hello everyone, I would just like a push in the right direction here with my homework assignment. Here is the question: (1) Write a C function called input which returns void, this function prompts the user for input of two integers followed by a double precision value. This function reads these values from the keyboard and finds the product of the two integers entered. The function uses call by reference to communicate the values of the three values read and the product calculated back to the main program. The main program then prints the three values read and the product calculated. Provide test results for the input: 3 5 23.5. Do not use arrays or global variables in your program. And here is my code: #include <stdio.h> #include <stdlib.h> void input(int *day, int *month, double *k, double *pro); int main(void){ int i,j; double k, pro; input(&i, &j, &k, &pro); printf("%f\n", pro); return 0; } void input(int *i, int *j, double *k, double *pro){ int x,y; double z; double product; scanf("%d", &x); scanf("%d", &y); scanf("%f", &z); *pro += (x * y * z); } I can't figure out how to reference the variables with pointers really, it is just not working out for me. Any help would be great!

    Read the article

  • Java Arrays.equals() returns false for two dimensional arrays.

    - by Achilles
    Hi there, I was just curious to know - why does Arrays.equals(double[][], double[][]) return false? when in fact the arrays have the same number of elements and each element is the same? For example I performed the following test. ` [java] double[][] a, b; int size =5; a=new double[size][size]; b=new double[size][size]; for( int i = 0; i < size; i++ ) for( int j = 0; j < size; j++ ){ a[i][j]=1.0; b[i][j]=1.0; } if(Arrays.equals(a, b)) System.out.println("Equal"); else System.out.println("Not-equal"); [/java] ` Returns false and prints "Not-equal. on the other hand, if I have something like this: [java] double[] a, b; int size =5; a=new double[size]; b=new double[size]; for( int i = 0; i < size; i++ ){ a[i]=1.0; b[i]=1.0; } if(Arrays.equals(a, b)) System.out.println("Equal"); else System.out.println("Not-equal"); } [/java] returns true and prints "Equal". Does the method only work with single dimensions? if so, is there something similar for multi-dimensional arrays in Java?

    Read the article

  • C++ Returning a Reference

    - by Devil Jin
    Consider the following code where I am returning double& and a string&. The thing works fine in the case of a double but not in the case of a string. Why is this difference in the behavior? In both the cases compiler does not even throws the Warning: returning address of local variable or temporary as I am returning a reference. #include <iostream> #include <string> using namespace std; double &getDouble(){ double h = 46.5; double &hours = h; return hours; } string &getString(){ string str = "Devil Jin"; string &refStr = str; return refStr; } int main(){ double d = getDouble(); cout << "Double = " << d << endl; string str = getString(); cout << "String = " << str.c_str() << endl; return 0; } Output: $ ./a.exe Double = 46.5 String =

    Read the article

  • Image resizing - sometimes very poor quality?!

    - by eWolf
    I'm resizing some images to the screen resolution of the user; if the aspect ratio is wrong, the image should be cut. My code looks like this: protected void ConvertToBitmap(string filename) { var origImg = System.Drawing.Image.FromFile(filename); var widthDivisor = (double)origImg.Width / (double)System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width; var heightDivisor = (double)origImg.Height / (double)System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height; int newWidth, newHeight; if (widthDivisor < heightDivisor) { newWidth = (int)((double)origImg.Width / widthDivisor); newHeight = (int)((double)origImg.Height / widthDivisor); } else { newWidth = (int)((double)origImg.Width / heightDivisor); newHeight = (int)((double)origImg.Height / heightDivisor); } var newImg = origImg.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero); newImg.Save(this.GetBitmapPath(filename), System.Drawing.Imaging.ImageFormat.Bmp); } In most cases, this works fine. But for some images, the result has an extremely poor quality. It looks like the would have been resized to something very small (thumbnail size) and enlarged again.. But the resolution of the image is correct. What can I do? Example orig image: Example resized image: Note: I have a WPF application but I use the WinForms function for resizing because it's easier and because I already need a reference to System.Windows.Forms for a tray icon.

    Read the article

  • C ] How can I handle weird errors from calculating acos / sin / atan2?

    - by Phrixus
    Has anyone seen this weird value while handling sin / cos/ tan / acos.. math stuff? ===THE WEIRD VALUE=== -1.#IND00 ===================== void inverse_pos(double x, double y, double& theta_one, double& theta_two) { // Assume that L1 = 350 and L2 = 250 double B = sqrt(x*x + y*y); double angle_beta = atan2(y, x); double angle_alpha = acos((L2*L2 - B*B - L1*L1) / (-2*B*L1)); theta_one = angle_beta + angle_alpha; theta_two = atan2((y-L1*sin(theta_one)), (x-L1*cos(theta_one))); } This is the code I was working on. In a particular condition - like when x & y are 10 & 10, this code stores -1.#IND00 into theta_one & theta_two. It doesn't look like either characters or numbers :( Without a doubt, atan2 / acos / stuff are the problems. But the problem is, try and catch doesn't work either cuz those double variables have successfully stored some values in them. Moreover, the following calculations never complain about it and never break the program! I'm thinking of forcing to use this value somehow and make the entire program crash... So that I can catch this error.. Except for that idea, I have no idea how I should check whether these theta_one and theta_two variables have stored this crazy values. Any good ideas? Thank you in advance..

    Read the article

  • give feedback on this pointer program

    - by JohnWong
    This is relatively simple program. But I want to get some feedback about how I can improve this program (if any), for example, unnecessary statements? #include<iostream> #include<fstream> using namespace std; double Average(double*,int); int main() { ifstream inFile("data2.txt"); const int SIZE = 4; double *array = new double(SIZE); double *temp; temp = array; for (int i = 0; i < SIZE; i++) { inFile >> *array++; } cout << "Average is: " << Average(temp, SIZE) << endl; } double Average(double *pointer, int x) { double sum = 0; for (int i = 0; i < x; i++) { sum += *pointer++; } return (sum/x); } The codes are valid and the program is working fine. But I just want to hear what you guys think, since most of you have more experience than I do (well I am only a freshman ... lol) Thanks.

    Read the article

  • optimize output value using a class and public member

    - by wiso
    Suppose you have a function, and you call it a lot of times, every time the function return a big object. I've optimized the problem using a functor that return void, and store the returning value in a public member: #include <vector> const int N = 100; std::vector<double> fun(const std::vector<double> & v, const int n) { std::vector<double> output = v; output[n] *= output[n]; return output; } class F { public: F() : output(N) {}; std::vector<double> output; void operator()(const std::vector<double> & v, const int n) { output = v; output[n] *= n; } }; int main() { std::vector<double> start(N,10.); std::vector<double> end(N); double a; // first solution for (unsigned long int i = 0; i != 10000000; ++i) a = fun(start, 2)[3]; // second solution F f; for (unsigned long int i = 0; i != 10000000; ++i) { f(start, 2); a = f.output[3]; } } Yes, I can use inline or optimize in an other way this problem, but here I want to stress on this problem: with the functor I declare and construct the output variable output only one time, using the function I do that every time it is called. The second solution is two time faster than the first with g++ -O1 or g++ -O2. What do you think about it, is it an ugly optimization?

    Read the article

  • How to mimic polymorphism in classes with template methods (c++)?

    - by davide
    in the problem i am facing i need something which works more or less like a polymorphic class, but which would allow for virtual template methods. the point is, i would like to create an array of subproblems, each one being solved by a different technique implemented in a different class, but holding the same interface, then pass a set of parameters (which are functions/functors - this is where templates jump up) to all the subproblems and get back a solution. if the parameters would be, e.g., ints, this would be something like: struct subproblem { ... virtual void solve (double& solution, double parameter)=0; } struct subproblem0: public subproblem { ... virtual void solve (double& solution, double parameter){...}; } struct subproblem1: public subproblem { ... virtual void solve (double* solution, double parameter){...}; } int main{ subproblem problem[2]; subproblem[0] = new subproblem0(); subproblem[1] = new subproblem1(); double argument0(0), argument1(1), sol0[2], sol1[2]; for(unsigned int i(0);i<2;++i) { problem[i]->solve( &(sol0[i]) , argument0); problem[i]->solve( &(sol1[i]) , argument1); } return 0; } but the problem is, i need the arguments to be something like Arg<T1,T2> argument0(f1,f2) and thus the solve method to be something of the likes of template<T1,T2> solve (double* solution, Arg<T1,T2> parameter) which cant obviously be declared virtual ( so cant be called from a pointer to the base class)... now i'm pretty stuck and don't know how to procede...

    Read the article

  • XAML PixelGrid to Prevent Blurry Text

    - by Bodekaer
    Hi, Just wanted to share a small Grid I created, which can help prevent blurry text etc. as it adjusts the margin of the Grid to ensure a pixel perfect position and size of the grid. Works great e.g. for inside StackPanels with auto height Labels/TextBlocks. Here is the code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace Controls { class PixelGrid : Grid { protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) { // POSITION Vector position = VisualTreeHelper.GetOffset(this); double targetX = Math.Round(position.X, MidpointRounding.ToEven); double targetY = Math.Round(position.Y, MidpointRounding.ToEven); double marginLeft = targetX - position.X; double marginTop = targetY - position.Y; // SIZE double targetHeight = Math.Round(sizeInfo.NewSize.Height, MidpointRounding.ToEven); double targetWidth = Math.Round(sizeInfo.NewSize.Width, MidpointRounding.ToEven); double marginBottom = targetHeight - sizeInfo.NewSize.Height; double marginRight = targetWidth - sizeInfo.NewSize.Width; // Adjust margin to ensure pixel width this.Margin = new Thickness(marginLeft, marginTop, marginRight, marginBottom); base.OnRenderSizeChanged(sizeInfo); } } }

    Read the article

  • C function prototype: void f(). Is it recommended?

    - by ycalleecharan
    Hi, I'm learning C and I saw in a book that a function prototype has the form void f() and in the function declaration or in the calling function, the f function takes arguments. Thus In the function declaration we have something like void f(long double y[], long double A) and in the calling function is f(y, A). The function is doing operations on the array y i.e. when the function is called, some elements in the array y are changing. A is just a constant numerical value that doesn't change. I have two questions: If defining the function prototype at the top in the program as void f() a good practice? Or is it better to put it as void f(long double y[], long double A) as in the function declaration? The called function f is changing elements in the array y. Is void the right return type? The program is working fine as such with the void as described. Or should I change all my "voids" to "long double". I'm working with long double as I need as much precision as possible though on my machine both double and long double gives me 15 precision digits. Thanks a lot

    Read the article

  • Disallow taking pointer/reference to const to a temporary object in C++ (no C++0X)

    - by KRao
    Hi, I am faced with the following issue. Consider the following class: //Will be similar to bost::reference_wrapper template<class T> class Ref { public: explicit Ref(T& t) : m_ptr(&t) {} private: T* m_ptr; }; and this function returning a double double fun() {return 1.0;} If we now have double x = 1.0; const double xc = 1.0; Ref<double> ref1(x); //OK Ref<const double> refc1(cx); //OK good so far, however: //Ref<double> ref2( fun() ); //Fails as I want it to Ref<const double> refc2( fun() ); //Works but I would like it not to Is there a way to modify Ref (the way you prefer) but not the function fun, so that the last line returns a compile-time error? Please notice you can modify the constructor signature (as long as I am able to initialise the Ref as intended). Thank you in advance for your help!

    Read the article

  • Computing the scalar product of two vectors in C++

    - by HowardRoark
    I am trying to write a program with a function double_product(vector<double> a, vector<double> b) that computes the scalar product of two vectors. The scalar product is $a_{0}b_{0}+a_{1}b_{1}+...+a_{n-1}b_{n-1}$. Here is what I have. It is a mess, but I am trying! #include <iostream> #include <vector> using namespace std; class Scalar_product { public: Scalar_product(vector<double> a, vector<double> b); }; double scalar_product(vector<double> a, vector<double> b) { double product = 0; for (int i = 0; i <= a.size()-1; i++) for (int i = 0; i <= b.size()-1; i++) product = product + (a[i])*(b[i]); return product; } int main() { cout << product << endl; return 0; }

    Read the article

  • When to pass pointers in functions?

    - by yCalleecharan
    scenario 1 Say my function declaration looks like this: void f(long double k[], long double y[], long double A, long double B) { k[0] = A * B; k[1] = A * y[1]; return; } where k and y are arrays, and A and B are numerical values that don't change. My calling function is f(k1, ya, A, B); Now, the function f is only modifying the array "k" or actually elements in the array k1 in the calling function. We see that A and B are numerical values that don't change values when f is called. scenario 2 If I use pointers on A and B, I have, the function declaration as void f(long double k[], long double y[], long double *A, long double *B) { k[0] = *A * *B; k[1] = *A * y[1]; return; } and the calling function is modified as f(k1, ya, &A, &B); I have two questions: Both scenarios 1 and 2 will work. In my opinion, scenario 1 is good when values A and B are not being modified by the function f while scenario 2 (passing A and B as pointers) is applicable when the function f is actually changing values of A and B due to some other operation like *A = *B + 2 in the function declaration. Am I thinking right? Both scenarios are can used equally only when A and B are not being changed in f. Am I right? Thanks a lot...

    Read the article

  • why Floating point exception?

    - by livio8495
    I have a floating point exception, and I don't know why. the code is this: void calcola_fitness(){ vector<double> fitness; int n=nodes.size(); int e=edges.size(); int dim=feasibility.size(); int feas=(feasibility[dim-1])*100; int narchi=numarchicoll[dim-1]/e; int numero_nodi=freePathNode.size()/n; double dist_start_goal=node_dist(0,1); int i,f,t; double pathlenght=0; int siize=freePathNode.size(); for(i=0;i!=siize-1; i++){ f=freePathNode[i].getIndex(); i++; t=freePathNode[i].getIndex(); i--; pathlenght=pathlenght+node_dist(f,t); } double pathlenghtnorm=pathlenght/10*dist_start_goal; double fit=((double)numero_nodi+pathlenghtnorm+(double)narchi)*((double)feas); fitness.push_back(fit); } Could anybody help me? What's the problem? I could I solve this? thank you very much

    Read the article

< Previous Page | 34 35 36 37 38 39 40 41 42 43 44 45  | Next Page >