Mathf.Pow Shows Infinity on C# - c#

I'm trying to calculate a big number using Mathf.Pow() but when I place a breakpoint it shows infinity, I already tried using System.Numerics.BigInteger but it shows Big Integer cannot display infinity
Here's my code
using System;
using System.Numerics;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
//43
BigInteger res = new BigInteger(MathF.Pow(43, 27));
Console.WriteLine(res);
}
}
}

As Jeremy said
You could try BigInteger.Pow instead
I used BigInteger res = BigInteger.Pow(43,27); and that worked, thanks!

Related

System.ArgumentNullException: 'Value cannot be null. Parameter name: path' hackerrank solution aVeryBigSum

Where exactly is the problem? "System.ArgumentNullException: 'Value cannot be null.
Parameter name: path'" why could this be? Is there anyone who can help? Could the question have something to do with "Textwriter"?
here is my code
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;
class Result
{
/*
* Complete the 'aVeryBigSum' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts LONG_INTEGER_ARRAY ar as parameter.
*/
public static long aVeryBigSum(List<long> ar)
{
long sum=0;
for(int i=0; i<= ar.Count;i++) {
sum += ar[i];
}
return sum;
}
}
class Solution
{
public static void Main(string[] args)
{
TextWriter textWriter = new StreamWriter(#System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
int arCount = Convert.ToInt32(Console.ReadLine().Trim());
List<long> ar = Console.ReadLine().TrimEnd().Split(' ').ToList().Select(arTemp => Convert.ToInt64(arTemp)).ToList();
long result = Result.aVeryBigSum(ar);
textWriter.WriteLine(result);
textWriter.Flush();
textWriter.Close();
}
}
I just ran your solution directly on Hackerrank and it does not throw that exception, so I would assume that you are running it locally.
When you run those solutions locally you need to be careful with the Environment Variables.
In this case the program expects an Environment Variable called OUTPUT_PATH which you probably did not set on your machine, but it is set on Hackerrank.
According to Microsoft, Environment.GetEnvironmentVariable returns:
The value of the environment variable specified by variable, or null if the environment variable is not found.
ı solved the problem. change the function like this:
public static long aVeryBigSum(List<long> ar)
{
long sum=0;
foreach(long item in ar) {
sum = sum +item;
}
return sum;
}

False value from User Input

I am trying to save the value i get through Console.Read() in an Integer, but whatever i type in my keyboard, the console always gives out 13. I tried to copy an example code, which definitly has to work, but im still only getting 13 as value.
using System;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.Read();
int Test = Console.Read();
Console.WriteLine(Test);
}
}
}
After i typed in a number, it always shows '13' in the console.
Console.Read() reads first character from input stream.
In your case, You are trying to convert second character of input stream(i.e.after first Console.Read()) which is Carriage return and its ASCII value is 13, Test variable which is of type int, storing carriage return in integer format. i.e 13
If you want to convert first character from input stream, then try below
using System;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
int Test = Console.Read(); //Or you can use Console.ReadLine() to read entire line.
Console.WriteLine(Test);//Print first character of input stream
}
}
}
Here, you have to use Console.ReadLine to read the number. As Console.ReadLine returns string, you have to convert it to Int32. The following code will fix the issue
using System;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
int Test = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(Test);
}
}
}
Try changing this to:
using System;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
int Test = Console.ReadLine();
Console.WriteLine(Test);
}
}
}
Since 13 is key code for enter, you are probably getting that number from trying to read the whole line.

ml.net sentiment analysis warning about format errors & bad values

I've been having a problem with my ml.net console app. This is my first time using ml.net in Visual Studio so I was following this tutorial from microsoft.com, which is a sentiment analysis using binary classification.
I'm trying to process some test data in the form of tsv files to get a positive or negative sentiment analysis, but in debugging I'm receiving warnings there being 1 format error and 2 bad values.
I decided to ask all you great devs here on Stack to see if anyone can help me find a solution.
Here's an image of the debugging below:
Here's the link to my test data:
wiki-data
wiki-test-data
Finally, here's my code for those who what to reproduce the problem:
There's 2 c# files: SentimentData.cs & Program.cs.
1 - SentimentData.cs:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.ML.Runtime.Api;
namespace MachineLearningTut
{
public class SentimentData
{
[Column(ordinal: "0")]
public string SentimentText;
[Column(ordinal: "1", name: "Label")]
public float Sentiment;
}
public class SentimentPrediction
{
[ColumnName("PredictedLabel")]
public bool Sentiment;
}
}
2 - Program.cs:
using System;
using Microsoft.ML.Models;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.Api;
using Microsoft.ML.Trainers;
using Microsoft.ML.Transforms;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ML;
using Microsoft.ML.Data;
using System.Threading.Tasks;
namespace MachineLearningTut
{
class Program
{
const string _dataPath = #".\Data\wikipedia-detox-250-line-data.tsv";
const string _testDataPath = #".\Data\wikipedia-detox-250-line-test.tsv";
const string _modelpath = #".\Data\Model.zip";
static async Task Main(string[] args)
{
var model = await TrainAsync();
Evaluate(model);
Predict(model);
}
public static async Task<PredictionModel<SentimentData, SentimentPrediction>> TrainAsync()
{
var pipeline = new LearningPipeline();
pipeline.Add(new TextLoader (_dataPath).CreateFrom<SentimentData>());
pipeline.Add(new TextFeaturizer("Features", "SentimentText"));
pipeline.Add(new FastForestBinaryClassifier() { NumLeaves = 5, NumTrees = 5, MinDocumentsInLeafs = 2 });
PredictionModel<SentimentData, SentimentPrediction> model = pipeline.Train<SentimentData, SentimentPrediction>();
await model.WriteAsync(path: _modelpath);
return model;
}
public static void Evaluate(PredictionModel<SentimentData, SentimentPrediction> model)
{
var testData = new TextLoader(_testDataPath).CreateFrom<SentimentData>();
var evaluator = new BinaryClassificationEvaluator();
BinaryClassificationMetrics metrics = evaluator.Evaluate(model, testData);
Console.WriteLine();
Console.WriteLine("PredictionModel quality metrics evaluation");
Console.WriteLine("-------------------------------------");
Console.WriteLine($"Accuracy: {metrics.Accuracy:P2}");
Console.WriteLine($"Auc: {metrics.Auc:P2}");
Console.WriteLine($"F1Score: {metrics.F1Score:P2}");
}
public static void Predict(PredictionModel<SentimentData, SentimentPrediction> model)
{
IEnumerable<SentimentData> sentiments = new[]
{
new SentimentData
{
SentimentText = "Please refrain from adding nonsense to Wikipedia."
},
new SentimentData
{
SentimentText = "He is the best, and the article should say that."
}
};
IEnumerable<SentimentPrediction> predictions = model.Predict(sentiments);
Console.WriteLine();
Console.WriteLine("Sentiment Predictions");
Console.WriteLine("---------------------");
var sentimentsAndPredictions = sentiments.Zip(predictions, (sentiment, prediction) => (sentiment, prediction));
foreach (var item in sentimentsAndPredictions)
{
Console.WriteLine($"Sentiment: {item.sentiment.SentimentText} | Prediction: {(item.prediction.Sentiment ? "Positive" : "Negative")}");
}
Console.WriteLine();
}
}
}
If anyone would like to see the code or more details on the solution, ask me on the chat and I'll send it. Thanks in advance!!! [Throws a Thumbs Up]
I think I got a fix for you. A couple of things to update:
First, I think you got your SentimentData properties switched to what the data has. Try changing it to
[Column(ordinal: "0", name: "Label")]
public float Sentiment;
[Column(ordinal: "1")]
public string SentimentText;
Second, use the useHeader parameter in the TextLoader.CreateFrom method. Don't forget to add that to the other one for the validation data, as well.
pipeline.Add(new TextLoader(_dataPath).CreateFrom<SentimentData>(useHeader: true));
With those two updates, I got the below output. Looks like a nice model with an AUC of 85%!
Another thing that helps with text type datasets is indicating that the text has quotes:
TextLoader("someFile.txt").CreateFrom<Input>(useHeader: true, allowQuotedStrings: true)
There is bad formated value on 252 and 253 rows. May me there fields wich contains the delimiter charachter.
If you post code or sample data we can be more precise.

C#, basic error

So I am making a super basic (I'm in my second week of learning C# so please excuse my ignorance) program that takes a string input from a user and outputs the string backwards. I have copied the book to a T in regards to a majority of it but I have noticed spelling errors in some of their code so I don't have a lot of faith in what they are showing. My compiler is giving me an error with WriteLine and ReadLine and I don't understand why as the book says it works. This is the error I am getting;
"WriteLine does not exist in the current context" same with "ReadLine"
My code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
static class funcStrings
{
public static string ReverseString(string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
}
class runProgram
{
class Program
{
static void Main()
{
string name;
WriteLine("Enter your name to be reversed ");
name = ReadLine();
Console.WriteLine(funcStrings.ReverseString(name));
}
}
}
}
Thanks for any guidance here
You just need to add Console. in front:
Console.WriteLine("Enter your name to be reversed ");
name = Console.ReadLine();
You can add such namespace:
using static System.Console;
This brings all the static members from the System.Console class into scope, so that you don't need to prefix them with Console. It is a C# 6 feature, and useful when accessing many members in a static class. See relevant documentation.
The problem is probably that it should be Console.WriteLine and Console.ReadLine.
Currently it is:
static void Main()
{
string name;
WriteLine("Enter your name to be reversed ");
name = ReadLine();
Console.WriteLine(funcStrings.ReverseString(name));
}
You need to add a Console.WriteLine("Enter your name to be reversed"):

Issue trying to solve Project Euler #1

I'm having a problem trying to make a small app to solve Project Euler Problem #1.
Whenever I attempt to run this, it returns as 0, instead of 233168.
I'm not necessarily looking for an absolute answer, just some hints, I'm trying to learn.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x;
List<int> listOne = new List<int>();
for (x = 1; x < 1000; ++x)
{
if(x%3 == 0 || x%5 == 0)
{
listOne.Add(x);
}
Console.WriteLine(listOne.Sum());
Console.ReadLine();
}
}
}
}
In the interests of helping you learn, I'm not going to provide the exact answer.
Have a look at the scoping of your Console.WriteLine() statement. My guess is that it's not running when you think it should be.

Categories

Resources