Problem with the output of an exponential calculation - python-3.x

I tried to calculate an exponential calculation, I tried both ways, writing it with the normal ** operator and the pow() function.
If I directly use numbers, everything works completely fine. But as soon as I use variables which get their value from input() functions the result is rounded, although I use the float argument.
I am quite new to coding, so please don't go to hard on me.
Code below:
pow(1.05,5), everything fine, result is 1.2762815625 and so on
float(pow(int(a),int(b)) the result is just 1.0, although it should be the same as above.

it is because you are doing the power operation on int i.e first you are converting the 1.05 to 1 by doing int(1.05) and then calculating the power(). you need to apply pow() on float()
print(float(pow(float(1.05),float(5))))
or either
print(pow(float(1.05),float(5)))

The reason the float function returns 1.0 is because of how it deals with integers.
For example:
integer = 5.5236734
print(float(integer))
The above code's output will be:
5.5236734
Now lets say you make some changes:
integer = 5.5236734
print(int(integer))
First, we made integer a decimal number, and then we said to print the int() form of the decimal.
This will be the result:
5
So, to fix your code, you just need to do this:
a = 1.05
b = 5
print(float(pow(a, b)))
Which will output:
1.2762815625000004
Hope this helps!

Related

Online GDB for Fortran: Error: Symbol ‘average1’ at (1) already has basic type of REAL [duplicate]

I have this function, depicted below. It passes in two vectors with three values each, and should pass out one vector with three values as well. I call the function like this:
Fr = Flux(W(:,i),W(:,i+1))
What I have realized through messing around with the code, trying pure functions, and modules, and researching the error statement (that I will include at the bottom), is that fortran is reading my function Flux, and thinks that the input vectors are an attempt to call an entry from the array. That is my best guess as to what is going on. I asked around the lab and most people suggested using subroutines, but that seemed clunky, and I figured there should probably be a more elegant way, but I have not yet found it. I tried to define a result by saying:
DOUBLE PRECISION FUNCTION Flux(W1,W2) Result(FluxArray(3))
and then returning fluxarray but that does not work, as fortran cannot understand the syntax
The actual Function is this:
DOUBLE PRECISION FUNCTION Flux(W1,W2)
USE parameters
IMPLICIT NONE
DOUBLE PRECISION, DIMENSION(3), INTENT(IN)::W1, W2
DOUBLE PRECISION, DIMENSION(3), INTENT(OUT):: Flux
DOUBLE PRECISION, DIMENSION(3):: F1, F2
DOUBLE PRECISION::U1,U2,Rh1,Rh2,P1,P2,E1,E2,Rh,P,u,c,Lambda
INTEGER:: k
U1=W1(2)/W1(1)
U2=W2(2)/W2(1)
Rh1=W1(1)
Rh2=W2(1)
P1=(gamma_constant-1.d0)*(W1(3)-.5d0*Rh1*U1**2)
P2=(gamma_constant-1.d0)*(W2(3)-.5d0*Rh2*U2**2)
E1=W1(3)
E2=W2(3)
F1=[Rh1*U1,Rh1*U1**2+P1,(E1+P1)*U1]
F2=[Rh2*U2,Rh2*U2**2+P2,(E2+P2)*U2]
Rh=.5d0*(Rh1+Rh2)
P=.5d0*(P1+P2)
u=.5d0*(U1+U2)
c=sqrt(gamma_constant*P/Rh)
Lambda=max(u, u+c, u-c)
do k=1,3,1
Flux(k)=.5d0*(F1(k)+F2(k))-.5d0*eps*Lambda*(W2(k)-W1(k))
end do
RETURN
END FUNCTION Flux
Here is the error statement:
Quasi1DEuler.f90:191.51:
DOUBLE PRECISION, DIMENSION(3), INTENT(OUT):: Flux
1
Error: Symbol 'flux' at (1) already has basic type of REAL
Quasi1DEuler.f90:217.58:
Flux(k)=.5d0*(F1(k)+F2(k))-.5d0*eps*Lambda*(W2(k)-W1(k))
1
Error: Unexpected STATEMENT FUNCTION statement at (1)
Quasi1DEuler.f90:76.18:
Fr = Flux(W(:,i),W(:,i+1))
The last error occurs for both Fr and Fl. Thank you for your time and any help or consideration you can give!
EDIT/Follow-up::
Thanks for the help, I don't know a better way to present this so I'm going to edit the initial question.
I did as you suggested and It solved that issue, now it says:
Fr = Flux(W(:,i),W(:,i+1))
1
Error: The reference to function 'flux' at (1) either needs an explicit INTERFACE or the rank is incorrect
I saw a similar issue on SO at this link:
Computing the cross product of two vectors in Fortran 90
where they suggested that he put all his functions into modules. is there a better/simpler way for me to fix this error?
With RESULT(FluxArray), fluxArray is the name of the result variable. As such, your attempt to declare the characteristics in the result clause are mis-placed.
Instead, the result variable should be specified within the function body:
function Flux(W1,W2) result(fluxArray)
double precision, dimension(3), intent(in)::W1, W2
double precision, dimension(3) :: fluxArray ! Note, no intent for result.
end function Flux
Yes, one can declare the type of the result variable in the function statement, but the array-ness cannot be declared there. I wouldn't recommend having a distinct dimension statement in the function body for the result variable.
Note that, when referencing a function returning an array it is required that there be an explicit interface available to the caller. One way is to place the function in a module which is used. See elsewhere on SO, or language tutorials, for more details.
Coming to the errors from your question without the result.
DOUBLE PRECISION FUNCTION Flux(W1,W2)
DOUBLE PRECISION, DIMENSION(3), INTENT(OUT):: Flux
Here the type of Flux has been declared twice. Also, it isn't a dummy argument to the function, so as above it need not have the intent attribute.
One could write
FUNCTION Flux(W1,W2)
DOUBLE PRECISION, DIMENSION(3) :: Flux ! Deleting intent
or (shudder)
DOUBLE PRECISION FUNCTION Flux(W1,W2)
DIMENSION :: Flux(3)
The complaint about a statement function is unimportant here, following on from the bad declaration.

Arduino and TinyGPS++ convert lat and long to a string

I' m having a problem parsing the lat and long cords from TinyGPS++ to a Double or a string. The code that i'm using is:
String latt = ((gps.location.lat(),6));
String lngg = ((gps.location.lng(),6));
Serial.println(latt);
Serial.println(lngg);
The output that i'm getting is:
0.06
Does somebody know what i'm doing wrong? Does it have something to do with rounding? (Math.Round) function in Arduino.
Thanks!
There are two problems:
1. This does not compile:
String latt = ((gps.location.lat(),6));
The error I get is
Wouter.ino:4: warning: left-hand operand of comma has no effect
Wouter:4: error: invalid conversion from 'int' to 'const char*'
Wouter:4: error: initializing argument 1 of 'String::String(const char*)'
There is nothing in the definition of the String class that would allow this statement. I was unable to reproduce printing values of 0.06 (in your question) or 0.006 (in a later comment). Please edit your post to have the exact code that compiles, runs and prints those values.
2. You are unintentionally using the comma operator.
There are two places a comma can be used: to separate arguments to a function call, and to separate multiple expressions which evaluate to the last expression.
You're not calling a function here, so it is the latter use. What does that mean? Here's an example:
int x = (1+y, 2*y, 3+(int)sin(y), 4);
The variable x will be assigned the value of the last expression, 4. There are very few reasons that anyone would actually use the comma operator in this way. It is much more understandable to write:
int x;
1+y; // Just a calculation, result never used
2*y; // Just a calculation, result never used
3 + (int) sin(y); // Just a calculation, result never used
x = 4; // A (trivial) calculation, result stored in 'x'
The compiler will usually optimize out the first 3 statements and only generate code for the last one1. I usually see the comma operator in #define macros that are trying to avoid multiple statements.
For your code, the compiler sees this
((gps.location.lat(),6))
And evaluates it as a call to gps.location.lat(), which returns a double value. The compiler throws this value away, and even warns you that it "has no effect."
Next, it sees a 6, which is the actual value of this expression. The parentheses get popped, leaving the 6 value to be assigned to the left-hand side of the statement, String latt =.
If you look at the declaration of String, it does not define how to take an int like 6 and either construct a new String, or assign it 6. The compiler sees that String can be constructed from const char *, so it tells you that it can't convert a numeric 6 to a const char *.
Unlike a compiler, I think I can understand what you intended:
double latt = gps.location.lat();
double lngg = gps.location.lon();
Serial.println( latt, 6 );
Serial.println( lngg, 6 );
The 6 is intended as an argument to Serial.println. And those arguments are correctly separated by a comma.
As a further bonus, it does not use the String class, which will undoubtedly cause headaches later. Really, don't use String. Instead, hold on to numeric values, like ints and floats, and convert them to text at the last possible moment (e.g, with println).
I have often wished for a compiler that would do what I mean, not what I say. :D
1 Depending on y's type, evaluating the expression 2*y may have side effects that cannot be optimized away. The streaming operator << is a good example of a mathematical operator (left shift) with side effects that cannot be optimized away.
And in your code, calling gps.location.lat() may have modified something internal to the gps or location classes, so the compiler may not have optimized the function call away.
In all cases, the result of the call is not assigned because only the last expression value (the 6) is used for assignment.

Excel VBA failure of repeated Evaluate method

I have written a little tool in VBA that charts a function you pass it as a string (e.g. "1/(1+x)" or "exp(-x^2)"). I use the built-in Evaluate method to parse the formula. The nub of it is this function, which evaluates a function of some variable at a given value:
Function eval(func As String, variable As String, value As Double) As Double
eval = Evaluate(Replace(func, variable, value))
End Function
This works fine, e.g. eval("x^2, "x", 2) = 4. I apply it element-wise down an array of x values to generate the graph of the function.
Now I want to enable my tool to chart the definite integral of a function. I have created an integrate function which takes an input formula string and uses Evaluate to evaluate it at various points and approximate the integral. My actual integrate function uses the trapezoidal rule, but for simplicity's sake let's suppose it is this:
Function integrate(func As String, variable As String, value As Double) As Double
integrate = value * (eval(func, variable, 0) + eval(func, variable, value)) / 2
End Function
This also works as expected, e.g. integrate("t", "t", 2) = 2 for the area of the triangle under the identity function.
The problem arises when I try to run integrate through the charting routine. When VBA encounters a line like this
eval("integrate(""t"",""t"",x)", "x", 2)
then it will stop with no error warning when Evaluate is called inside the eval function. (The internal quotes have to be doubled up to read the formula properly.) I expect to get the value 2 since Evaluate appears to try and evaluate integrate("t", "t", 2)
I suspect the problem is with second call on Evaluate inside integrate, but I've been going round in circles trying to figure it out. I know Evaluate is finicky and poorly documented http://fastexcel.wordpress.com/2011/11/02/evaluate-functions-and-formulas-fun-how-to-make-excels-evaluate-method-twice-as-fast but can anyone think of a way round this?
Thanks
George
Excel 2010 V14, VBA 7.0
Thanks Chris, your Debug.Print suggestion got me thinking and I narrowed the problem down a bit more. It does seem like Evaluate gets called twice, as this example shows:
Function g() As Variant
Debug.Print "g"
g = 1
End Function
Run from the Immediate Window:
?Evaluate("g()")
g
g
1
I found this http://www.decisionmodels.com/calcsecretsh.htm which shows a way round this by using Worksheet.Evaluate (Evaluate is actually the default for Application.Evaluate):
?ActiveSheet.Evaluate("g()+0")
g
1
However this still doesn't solve the problem with Evaluate calling itself. Define
Function f() As Variant
Debug.Print "f"
f = ActiveSheet.Evaluate("g()+0")
End Function
Then in the Immediate Window:
?ActiveSheet.Evaluate("f()+0")
f
Error 2015
The solution I found was define a different function for the second formula evaluation:
Function eval2(formula As String) As Variant
[A1] = "=" & formula
eval2 = [A1]
End Function
This still uses Excel's internal evaluation mechanism, but via a worksheet cell calculation. Then I get what I want:
?eval2("f()")
f
g
1
It's slower due to the repeated worksheet hits, but that's the best I can do. So in my original example, I use eval to calculate the integral and eval2 to chart it. Still interested if anyone has any other suggestions.

Primitive Integer Operation

I am trying to compare 2 sets of element related by a binary relation which as an effect that
#set1 = #set0 + 2
Apparently in this expression the 2 is interpreted as {}, that is what the evaluator tells me, so the expression returns true.
The book says that + arithmetic operator is detected automatically. But apparently the problem is more about how to express the 2 in arithmetic. In the book I saw an example which is exactly what I want to do.
Moreover, when I calculate #Set, which contains set1+set0 the evaluator returns me a negative value.
Does someone have an idea about this?
Thanks in advance.
Try this:
sig A {}
sig B {}
pred show{ #A = add[#B, 2]}
run show for 5
As far as I understand there is special function for adding integers.
Let me know if I understood you right.

While loop in Python converting integer to a string?

So I can't seem to get this. Without the 'while' loop this code works fine but as soon as I apply the loop it stops working right. From some reason it's treating x as a string. Like if x were 2 it would print y as '2222' instead of 16. I'm still new at this can someone tell my why? Thanks!
go = 'y'
while go == 'y':
print('enter x')
x = input()
y = x * 4
print(y)
print('go again?')
go = input()
Python 3's input function always returns a string. This is a change from Python 2, where input returned different kinds of Python objects depending on what was entered by the user. Python 3's version is equivalent to Python 2's raw_input.
With that background in mind, it's easy to fix your code. Just call the int constructor to turn your string into an integer. Or if you want to support non-integer values (like 1.4), use float instead.
As an aside, as your code is currently formatted in the question, it has an infinate loop. Is your logic to change the go variable really at top level? If so, it won't ever change during the loop, which will run forever.
This is actually dependent on your python version. input will automatically convert your string to an integer if it finds one. To prevent this, use the raw_input function in python < 3. For python 3 and above I believe this is the default behavior.

Resources